![]() |
VOOZH | about |
Socket programming in Java enables communication between two devices over a network by establishing a connection between a client and a server using the java.net package. It forms the foundation for building distributed applications.
To connect to another machine we need a socket connection. A socket connection means both machines know each other’s IP address and TCP port. The java.net.Socket class is used to create a socket.
Socket socket = new Socket(“127.0.0.1”, 5000)
To exchange data over a socket connection, streams are used for input and output:
Example to access these streams:
// to read data
InputStream input = socket.getInputStream();
// to send data
OutputStream output = socket.getOutputStream();
The socket connection is closed explicitly once the message to the server is sent.
Example:
java.net.ConnectException: Connection refused (Connection refused)
To create a server application two sockets are needed.
ServerSocket: This socket waits for incoming client requests. It listens for connections on a specific port.Socket: Once a connection is established, the server uses this socket to communicate with the client.Once communication is finished, it's important to close the socket and the input/output streams to free up resources.
Example:
Explanation: In the above example, we have implemented a server that listens on a specific port, accepts a client connection, and reads messages sent by the client. The server displays the messages until "Over" is received, after which it closes the connection and terminates.
Important Points:
Open two windows one for Server and another for Client.
First run the Server application as:
$ java Server
Output:
Server started
Waiting for a client ...
Then run the Client application on another terminal as
$ java Client
Output:
Connected
Here is a sample interaction:
Client:
Hello
I made my first socket connection
Over
Server:
Hello
I made my first socket connection
Over
Closing connection
Sending “Over” closes the connection between the Client and the Server just like said before.
Note : If you're using Eclipse or likes of such: