- Distributed Computing in Java 9
- Raja Malleswara Rao Pattamsetti
- 275字
- 2021-07-02 21:02:31
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:
- The ServerSocket object is instantiated by the server with a port number for communication:
ServerSocket server = new ServerSocket( PORT );
- 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();
- After this, the client instantiates Socket with the server IP address and port number:
Socket client = new Socket(server, portid);
- 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.
- 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.
- 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”);
- Close the socket when the data exchange is complete:
client.close();
推薦閱讀
- 軟件架構設計:大型網站技術架構與業務架構融合之道
- 大學計算機基礎實驗教程
- STM32F0實戰:基于HAL庫開發
- Spring Boot進階:原理、實戰與面試題分析
- 組態軟件技術與應用
- Mastering Unity 2D Game Development(Second Edition)
- iOS自動化測試實戰:基于Appium、Python與Pytest
- Java Fundamentals
- Node.js區塊鏈開發
- Web開發新體驗
- Python輕松學:爬蟲、游戲與架站
- 區塊鏈原理與技術應用
- Java EE 8 Development with Eclipse
- jQuery Mobile從入門到精通
- Mastering Java 11