Socket programming provides the communication mechanism between computers using network. A client socket program creates a socket at its end of the communication and using that client socket it will connect to server socket.
When the connection is successfully established, the server will creates a socket object at its end of the communication. The client and server will now communicate writing and reading messages.
The java.net.Socket class contains a socket functionality, and the java.net.ServerSocket class gives a mechanism for the server program to listen for clients and establish connections.
Below are the steps for establishing connection between client and server using Socket :
After the connections is successfully established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP Network is a two way communication protocol, so data can be sent across both sides at the same time.
Below are the classes providing complete set of methods to implement socket programming.
The java.net.ServerSocket class is used by server applications to listen for client.
ServerSocket class has 4 constructors that are :
ServerSocket Methods :-
Methods of ServerSocket class are as follows:
Socket Class :
Socket class has five constructors that is client uses for connect to a server:
Methods of Socket class are as follows: