官术网_书友最值得收藏!

Socket programming for TCP

The java.net.Socket class represents a socket, and the java.net.ServerSocket class represents a server socket through which the server can listen to client sockets and establish a connection with them:

The following are the steps that occur when the connection is established:

  1. The ServerSocket object is instantiated by the server with a port number for communication:
        ServerSocket server = new ServerSocket( PORT );
  1. The server calls the accept() method of ServerSocket and waits until the client connects to a given port. This is called server listening on a given port:
        Socket serverclient = server.accept();
  1. After this, the client instantiates Socket with the server IP address and port number:
        Socket client = new Socket(server, portid);
  1. Then, the constructor of the Socket object tries to connect to the client with the server on a given port number. On successful connection, CLIENT has the Socket object through which it can communicate with SERVER.
  2. The accept() method of the ServerSocket object on the server side returns a reference to new Socket, which is connected to the client's socket.
  3. Once connected, the communication occurs through Java I/O streams; each socket has both OutputStream and InputStream. The server's java.io.OutputStream communicates with the client’s InputStream string and vice versa. As said earlier, in TCP, data flows in both directions at the same time:
        DataInputStream ips = new 
DataInputStream(client.getInputStream());
DataOutputStream ops = new
DataOutputStream(client.getOutputStream());
        Client receive: String line = is.readLine();
Client send: os.writeBytes(“Hello World!n”);
  1. Close the socket when the data exchange is complete:
        client.close();
主站蜘蛛池模板: 都昌县| 五莲县| 卫辉市| 木里| 丽水市| 溧水县| 乌苏市| 盐源县| 三亚市| 巩留县| 庄河市| 宣武区| 重庆市| 黄陵县| 新丰县| 调兵山市| 麻江县| 哈尔滨市| 镇康县| 克拉玛依市| 万安县| 东城区| 繁昌县| 承德市| 缙云县| 惠州市| 奉化市| 旬阳县| 广饶县| 清丰县| 颍上县| 蒲江县| 郧西县| 长垣县| 同心县| 丹巴县| 马龙县| 云南省| 伊春市| 阿图什市| 普宁市|