Java Socket Programming – Upgrade your programming skills in Java
In our last Java tutorial, we discussed the Java URL class. In this tutorial, we will discuss the networking concept of Java programming, that is, Socket programming in Java along with its implementation.
We will earn to establish a Java Socket Connection. We will discuss both client-side and server-side socket programming in Java.
Socket Programming in Java
Socket programming refers to communication between two nodes or applications running on different JRE (Java Runtime Environment). We use the socket programming in Java to connect the client program with the server program, or simply, connect a client and a server.
Socket programming in Java can be either connection-oriented or connectionless. The package java.net is used for socket programming in Java. There are two classes in this package which are Socket class and ServerSocket class.
Every server is a software program running on a specific system that listens to a specific port and waits for the requests from the client-side. For example, the Tomcat server running on the port number 8080 responds to the requests coming on this port number.
The Java Socket Programming has two sections.
- Java Server Socket Program
- Java Client Socket Program
The following diagram shows the Socket Programming process:
What is a Socket in Java?
A socket in Java is one of the nodes of a two-way communication link between the client and server programs running on the network. An endpoint or a node is a combination of an IP address and a port number.
There is a port number for each socket so that the TCP layer can identify the application where to send the data.
Now, let’s discuss the two classes of java.net package in brief.
The java.net.Socket Class in Java
We use the Socket class to create the sockets for the client and server. The java.net.Socket class represents the socket. Both the client and the server programs use this socket to communicate with each other.
There are some methods in the Socket class.
Methods of Socket Class
S.N | Method | Description |
1 | public void connect(SocketAddress host, int timeout) throws IOException | This method connects the socket to the given input host. |
2 | public int getPort() | This method returns the port through which the socket is bound on the remote machine. |
3 | public int getLocalPort() | This method returns the port through which the socket is bound on the local machine. |
4 | public SocketAddress getRemoteSocketAddress() | This method gives the address of the remote socket. |
5 | public InputStream getInputStream() throws IOException | This method returns the input stream of the socket. |
7 | public void close() throws IOException | This method closes the socket. Closing the socket makes it no longer available to connect it to any server. |
The java.net.ServerSocket Class in Java
The java.net.ServerSocket creates a server socket to obtain a port of the server and to listen to the client requests. The object of the ServerSocket class object helps to establish communication with the clients.
Methods of ServerSocket Class
S.N. | Method | Description |
1 | public int getLocalPort() | This method returns the port on which the server socket is listening to. |
2 | public Socket accept() throws IOException | It returns the socket and establishes a connection between the server and the client. |
3 | public void setSoTimeout(int timeout) | This method sets the time-out value for how long the server socket has to wait for a client during the accept() method. |
4 | public void bind(SocketAddress host, int backlog) | This method binds the socket to the specified server and port in the SocketAddress object. |
5 | public synchronized void close() | This method closes the object of the ServerSocket class. |
Client-Side Socket Programming
For implementing client-side programming, we need to follow the below steps:
- Create a Socket
- Connect it to ServerSocket by specifying the IP address and the port number
- Get the reference of the OutputStream
- Attach this reference to OutputStreamWriter
- Write and close
- Get the reference of InputStream
- Attach this reference to InputStreamWriter
- Read and Buffer
- Parse, interpret and process it
- Close Connection
1. Creating a Socket
To create a Socket, we use the Socket class and create its object. We pass the IP address and port number of the Server inside the Socket.
Here, we are using “localhost” because our server and the client applications are present on the same machine. For example:
Socket s=new Socket("localhost",6666);
2. Connecting socket to ServerSocket
After creating a socket, we connect it to the ServerSocket by passing the IP address and the port number.
3. Get the reference of the OutputStream
Now, we get the reference of the OutputStream for writing the request.
DataOutputStream out = null;
4. Attach this reference to OutputStreamWriter
Attach the reference of OutputStream to the OutputStreamWriter.
5. Write and close
With the reference of OutputStream, write the request and then close it:
out.write();
out.close();
6. Get the reference of the InputStream
Now, we get the reference of the InputStream for reading the request.
DataInputStream input = null;
7. Attach this reference to InputStreamWriter
Attach the reference of InputStream to the InputStreamReader.
8. Read and close
With the reference of InputStream, read the request a then close it:
input.readLine();
input.close();
9. Close the connection
After interpreting and parsing, close the connection
socket .close();
Server-Side Socket Programming
For implementing server-side programming, we need to follow the below steps:
- Create ServerSocket
- Bind it to a port number
- Put it into the listening mode
- Get the reference of InputStream
- Attach the reference to InputStreamReader
- Read and buffer
- Parse the request
- Prepare response
- Get the reference of OutputStream
- Attach the reference to OutputStreamReader
- Write the response
- Close Connection
Note: The 4th point only happens when there is a request from the client. Otherwise, the server ends at the 3rd stage only.
1. Creating a ServerSocket
To create a ServerSocket, we use the ServerSocket class and create its object.
ServerSocket server;
2. Binding it to a port number
After creating the object, we bind it to a port number through which the client can request it.
server = new ServerSocket(port);
3. Put it to the listening mode
Put the server into the listening mode so that it can listen to the requests coming from the client-side at the port number that we binded in the last step.
server.accept();
4. Get the reference of the OutputStream
Now, we get the reference of the OutputStream for writing the request.
DataOutputStream out = null;
5. Attach this reference to OutputStreamWriter
Attach the reference of OutputStream to the OutputStreamWriter.
6. Write the response
With the reference of OutputSteam, write the response:
7. Close the connection
After writing the response, close the connection
socket .close();
Now as we know the process of both client and server-side, we will implement them with the help of Java code.
Implementing Socket Programming in Java
Code for Server-side:
package com.techvidvan.socketprogramming; //A Java program for a Server Side import java.net.*; import java.io.*; public class ServerSide { //initialize socket and input stream private Socket socket = null; private ServerSocket server = null; private DataInputStream in = null; //constructor with port public ServerSide(int port) { //starts server and waits for a connection try { System.out.println("Server started at port 5100"); System.out.println("Waiting for a client ..."); socket = server.accept(); System.out.println("Client accepted"); //takes input from the client socket in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); String line = " "; //reads message from client until "Over" is sent while (!line.equals("Over")) { try { line = in.readUTF(); System.out.println(line); } catch(IOException i) { System.out.println(i); } } System.out.println("Closing connection"); //close connection socket.close(); in.close(); } catch(IOException i) { System.out.println(i); } } public static void main(String args[]){ ServerSide server = new ServerSide(5100); } }
Output:
Waiting for a client …
Code for Client-side:
package com.techvidvan.socketprogramming; //A Java program for a ClientSide import java.net.*; import java.io.*; public class ClientSide { //initialize socket and input output streams private Socket socket = null; private DataInputStream input = null; private DataOutputStream out = null; //constructor to put ip address and port @SuppressWarnings("deprecation") public ClientSide(String address, int port) { //establish a connection try { socket = new Socket(address, port); System.out.println("Connected"); //takes input from terminal input = new DataInputStream(System.in); //sends output to the socket out = new DataOutputStream(socket.getOutputStream()); } catch(UnknownHostException u) { System.out.println(u); } catch(IOException i) { System.out.println(i); } // string to read message from input String line = " "; //keep reading until "Over" is input while (!line.equals("Over")) { try { line = input.readLine(); out.writeUTF(line); } catch(IOException i) { System.out.println(i); } } //close the connection try { input.close(); out.close(); socket.close(); } catch(IOException i) { System.out.println(i); } } public static void main(String args[]) { ClientSide client = new ClientSide("localhost", 5230); } }
Output:
Important Points
- The server application makes the object of ServerSocket on port number 5230. Then, the server starts listening for client requests for port 5230.
- After that, the Server makes a Socket object to communicate with the client.
- The accept() method does not run unless the client program connects to the server.
- The getInputStream() method takes the input from the socket.
- The Server keeps receiving messages until the Client sends “Over”.
- In the end, we close the connection with the close() method. We close both the socket and the input stream.
- Compile both the Client and Server programs on your machine, and then, first, run the Server and then run the Client.
Summary
Socket Programming in Java is used to set the communication between the two nodes on the network. There are two important classes for Socket Programming in Java which is Socket and ServerSocket class. We covered various important methods of both the classes.
At last, we implemented the socket programming by connecting the client code with the server code. This article will surely help you to build and sharpen your concepts in Java Socket Programming.
Thank you for reading our article. Do share your feedback through the comment section below.
Happy Learning 🙂