socket详解

Server端:

1.创建套接字,socket()
2.分配套接字地址,bind()
3.等待连接请求,listen()
4.允许连接请求,accept()
5.读写数据,read()/write()
6.关闭连接,close()

Client端:

1.创建套接字,socket()
2.发起连接,connect()
3.读写数据,read()/write()
4.关闭连接,close()

Socket服务端:

public class Server {
    private ServerSocket serverSocket = null;
    private Socket socket = null;
    private DataInputStream input = null;

    public Server(int port) {
        try {
            //绑定端口
            serverSocket = new ServerSocket(port);
            //获取客户端连接请求
            socket = serverSocket.accept();
            input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            String line = "";
            while (!line.equals("exit")){
                //客户端通过writeUTF()写入数据
                line = input.readUTF();
                System.out.println("Server read: "+line);
            }
            System.out.println("socket closed.....");
            input.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        Server server = new Server(6000);
    }
}

Client客户端:

public class Client {
    private Socket socket = null;
    private DataOutputStream out = null;
    private BufferedReader input = null;

    public Client(String host,int port) {
        try {
            //与服务器建立连接
            socket = new Socket(host,port);
            input = new BufferedReader(new InputStreamReader(System.in));
            out = new DataOutputStream(socket.getOutputStream());
            String line = "";
            while (!line.equals("exit")){
                line = input.readLine();
                System.out.println("Client write: "+ line);
                out.writeUTF(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
             try {
                    out.close();
                    input.close();
                    socket.close();
                  } catch (Exception e) {
                         e.printStackTrace();
                  }
        }
    }
    public static void main(String[] args){
        Client client = new Client("localhost",6000);
    }
}