Questions
Please discuss the differences between handling Socket and ServerSocket.
1. Definitions
Before I go into the differences between handling Socket and ServerSocket, it would be helpful to explain the definitions of client, server, Socket, and ServerSocket.
As shown above, a client is a program that connects to a server by socket, and a server is a program that listens to the client socket and responds to the client (Eck, 2019). In Java, two classes help the communication between client and server: Socket and ServerSocket. Specifically, on the client-side, one can use the constructor Socket(String host, int port) of the Socket class to create a Socket object, and then use this object to call the getInputStream() or getOutputStream() to receive or send data; on the server-side, one can use the ServerSocket(int port) constructor of the ServerSocket class to create a ServerSocket object, and then call the accept() method to obtain the socket from the client. With this socket, the server can call getInputStream() or getOutputStream() to process data from the client or send data to the client.
2. Differences
The difference between handling Socket and ServerSocket is that: Socket is a class usually used on the client-side. One can communicate with the server by creating a Socket object and calling its getInputStream() or getOutputStream(); ServerSocket is a class used on the server-side. A person can use this class to create a ServerSocket object, treat it as a listener to receive socket from clients, and then process the received data and respond to the client. For example, the following code details handling Socket and ServerSocket.
Codes
The client program:
1 | import java.io.BufferedReader; |
The server program:
1 | import java.io.BufferedReader; |
Outputs
The client program’s outputs:
1 | Please enter the IP address: localhost |
The server program’s outputs:
1 | Hi, I am a message from the client. |
In the above code, the Client class creates a Socket object, calls the getOutputStream() method to send data to the server, and calls the getInputStream() method to receive the data from the server and print it out. Similarly, a ServerSocket object is created to receive the client’s socket in the Server class. Then, call the getOutputStream() method to send data to the client, and call the getInputStream() method to receive the data from the client and print it out.
Word count: 705
References
1.Eck, D. J. (2019). Introduction to Programming Using Java.
http://math.hws.edu/javanotes
2.Horstmann, C. S. 2019. Core Java Volume I–Fundamentals (11th ed.). Pearson.