Socket通信代码(原理)

1、运行环境:NetBeans IDE 6.0.1

2、说明:先运行服务器端,再运行客户端。

3、服务器端代码:

  新建java类Test

import java.net.*;

import java.io.*;

public class Test { //服务器端server

    public static void main(String[] args){   

        try{

            //server端的Socket与client对应的Socket进行通信

            ServerSocket server =new ServerSocket(8686);//侦听

            System.out.println("waiting for....");

            Socket socket =server.accept();//接收

            BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String input=reader.readLine();

            while(input!=null){

                System.out.println(input+"\n");

                input=reader.readLine();

            }

            reader.close();

            socket.close();

            server.close();

        }catch(Exception e){

            System.out.println("ServerSocket Exception"+e.getMessage());

        }

    }

}
View Code

4、客户端代码

  新建java类Test

import java.net.*;//用socket通信

import java.io.*;

public class Test { //客户端 client

    public static void main(String[] args){

        Socket socket =new Socket();

        try{

        socket.connect(new InetSocketAddress("localhost",8686));//连接服务器端(主机)

        PrintWriter writer=new PrintWriter(socket.getOutputStream(),true); //用来发送消息,用来对输入流的封装

        BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));//接受服务器端返回的信息,想将字节流转化成字节流

        String msg="GET /FirstWeb/ HTTP/1.1\n"+"Host: localhost:8686\n"+"\n";//http协议,空格和/都不能少,1.1是版本号

        writer.println(msg);//println,ln可以不写

        String input=reader.readLine();

        while(input!=null){

            System.out.println(input);

            input=reader.readLine();

        }  

        writer.close();

        reader.close();

        socket.close();

        }catch(Exception e){

            System.out.println("Exception"+e.getMessage());

        }

    }

}
View Code

 

 

你可能感兴趣的:(socket通信)