Socket Programming in Java

You might be quite anxious while getting to know about sockets in Java. But once, the concepts become crystal clear to you, there is no more difficulty in it. To give a short introduction to this topic, a socket is an interface between an application and a network. By combining an IP address and a port, we get a socket. This article elaborates on every detail of socket programming in Java.

What is Socket Programming in java?

To make the environment of server-client possible, socket programming plays a vital role. There are various classes that we must be aware of before diving deep into this concept.

Java Socket Class:

The Java Socket class is required to create a socket. The functioning of these sockets is to act as end-points for communication to take place between two machines.

Here are a few ways to initialize a socket class object:

  • Socket(): This method creates a socket.
  • Socket(InetAddress address, int port, InetAddress LocalAddress, int localport): This connects the local address and the port to the remote address and the remote port. The only requirement is that they must be on the same network.
  • Socket(InetAddress address, int port): It connects the IP address and the port to the local socket.
  • Socket(String host, int port, InetAddress localAddr, int localPort): It connects the socket to the host that is given in the constructor.

Important methods in Socket class in Java:

Method Description
public InputStream getInputStream() It returns the InputStream that is attached to the socket.
public OutputStream getOutputStream() It returns the OutputStream that is present in the socket.
public void connect(SocketAddress host, int timeout) throws IOException It connects the socket to give the input to the host.
public int getPort() It returns the port through which the socket is bound to the remote machine.
public int getLocalPort() It returns the port through which the socket is bound on the local machine.
public SocketAddress   getRemoteSocketAddress() It provides the remote socket’s address.
public close() throws IOException It closes the socket. Once this method is executed, the socket will no longer be able to connect to any server.

ServerSocket Class in Java:

The ServerSocket class is useful once we create a socket. Various methods that we require to accomplish this task are present in this class.

Every socket waits for a set of requests to get into the network. Once the request is obtained, it performs the operations and sends back the results. The weightlifting of the sockets is made by the “SocketImpl” class.

Methods Description
public Socket accept() throws IOException It returns the socket object and creates a connection between the client and the server.
public synchronized void close() It closes the connection.
public int getLocalPort() It returns the port on which the server is running.
public void setSoTimeout(int timeout) It sets the time-out value that denotes how long the server socket should wait for a client during the accept() method.
public void bind(SocketAddress host, int backlog) It binds the socket to the particular server and port in the SocketAddress object.

InetAddress Class Methods in Java:

The InetAddress class is dedicated to IP Addresses. A few important methods in this class are:

Methods Description
static InetAddress getByAddress(byte[]addr) It returns the InetAddress of the raw IP addresses.
static InetAddress getByAddress(String host, byte[]addr) It returns the InetAddress when the hostname and the IP address are present.
string getHostAddress() It returns the IP address in a string format.

Client and server:

The communication and socket connection takes place from two point-of-views, a server-side and the client-side. Now let us dive deep into the client-side programming.

Establishing a Socket Connection in Java:

To connect a machine to another machine, we must establish a socket connection. This enables two machines to contain information about each other’s network location and TCP Port. To represent a socket, we use the java.net.Socket class.

The way to open a socket is:

Socket socket = new Socket(“127.0.0.1”, 5000)
  • Here, the first argument, 127.0.01, is the IP address of the Server. The code runs on the IP address of the local host in a single stand-alone machine.
  • The second argument, 5000 is the TCP port. It is nothing but a number that represents the application to run on a server. This number can range anywhere between 0 to 65535.

1. Communication:

Communication is the main process that takes place here. To establish communication over a socket connection, the streams play a vital role in attaining input and output data.

2. Closing the connection:

To close a connection, the server requires a message insisting on it. once the server receives the message, the connection is closed.

Client-Side Socket Programming in Java:

To implement the client-side programming, the following steps should be followed.

1. Creation of a Socket in Java:

We can use the Socket class to create a Socket and its object. We pass the IP address and the port number of the Server to the Socket.
In this example, we use “localhost” as our server and the client applications are present on the same machine.

For example:

Socket s – new Socket(“locahost”, 6666);

2. Connecting socket to ServerSocket in java

Once the socket creation is done, we need to connect to the ServerSocket by passing the IP address and the port number.

3. Getting the reference of the OutputStream in Java:

Now, we obtain the reference of the OutputStream for writing the request.

For example:

DataOutputStream out = null;

4. Attach this reference to OutputStreamWriter in java:

Now, we can attach the reference of the OutputStream to the OutputStreamWriter.

5. Write and close in java:

Using the reference of OutputStream, we can write the request and then close it.

For example:

out.write();

out.close();

6. Getting the reference of the InputStream in java:

Now, we attain the reference of the InputStream to read the request.

7. Attach the reference to InputStreamWriter in Java:

Now we can attach the reference of InputStream to the InputStreamReader.

8. Read and close:

With the reference of the InputStream, we can read the request and close it.

For example:

input.readLine();

input.close();

9. Closing the connection:

Once the interpreting and parsing are over, we can close the connection.

socket.close();

Server-Side Socket Programming in Java:

To implement the server-side programming, the steps given below should be followed:

1. ServerSocket Creation:

To create a ServerSocket, we can use the ServerScoket class and create the object.

ServerSocket server;

2. Binding it to a port number:

Once the object is created, 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:

Now we must put the server into the listening mode. This lets us listen to the requests that come from the client-side at the port number which we bound in the last step.

server.accept();

4. Getting the reference of the OutputStream:

Now, we obtain the reference of the OutputStream to write the request.

DataOutputStream out = null;

5. Attaching the reference to the OutputStreamWriter:

We must attach the reference of the OutputStream to the outputStreamWriter.

6. Writing the response:

Using the reference of the outputStreamWriter, we can write the response.

7. Closing the connection:

Once the response is written, we can close the connection.

socket.close();

Sample program to implement Client programming in Java:

import java.net.*;
import java.io.*;
public class Client
{
private Socket socket = null;
private DataInputStream  input = null;
private DataOutputStream out = null;
public Client(String address, int port)
{
try{
socket = new Socket(address, port);
System.out.println("Connected");
input  = new DataInputStream(System.in);
out    = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u){
System.out.println(u);
}catch(IOException i)
{
System.out.println(i);
}
String line = "";
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}}
try{
input.close();
out.close();
socket.close();
}
catch(IOException i){
System.out.println(i);
}
}public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
}
}

Server Programming in java:

1. Establish a Socket Connection in Java:

In the case of a server application, we require two sockets.

  • A ServerSocket waits for the client requests.
  • A plain old Socket socket is required to communicate with the client.

2. Communication:

The getOutputStream() method sends the output via the socket.

3. Close the connection:

Once finished, the connection must be closed by closing the socket and the input/output streams.

Sample program to implement Server programming in Java:

import java.net.*;
import java.io.*;
public class Server
{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public Server(int port)
{
try{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[]){
Server server = new Server(5000);
}
}

Sample program to implement the use of Socket Programming in Java:

Server Side:

Server.java:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
System.out.println("Server Starts! The presence of any errors will be found on the screen. ");
try {
ServerSocket s = new ServerSocket(8080);
Socket sock=s.accept();
DataInputStream dis = new DataInputStream(sock.getInputStream());
String str = (String)dis.readUTF();
System.out.println("The message received is "+str);
s.close();
} catch (Exception e) {
System.out.println("An error occured!");
}
}
}

Client-Side:

import java.net.*;
import java.io.*;
public class Client 
{
public static void main(String[] args) {
try {
Socket clientsock=new Socket("localhost",8080);
DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
out.writeUTF("The client message: Welcome to Java tutorial with FirstCode!");
out.flush();
out.close();
clientsock.close();
} catch (Exception e) {
System.out.println("An error occured!");
System.out.println(e.getMessage());
} 
}
}

Output:

Server Starts! The presence of any errors will be found on the screen.
The client message: Welcome to Java tutorial with FirstCode!

Sending or receiving only one message is not a practical approach. The communication must be duplex to be effective. Here is a sample program to implement it.

 

import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String[] args) {
try
{
System.out.println("Server Starts!! The errors will be displayed on the screen ");
ServerSocket s = new ServerSocket(8080);
Socket sock=s.accept();
DataInputStream din = new DataInputStream(sock.getInputStream());
DataOutputStream dout = new DataOutputStream(sock.getOutputStream());
Scanner sc = new Scanner(System.in);
String mesgreceive="", mesgsent="";
while(true)
{
mesgreceive=din.readUTF();
System.out.println("Client Message:"+mesgreceive);
System.out.println("Please enter your message");
mesgsent=sc.nextLine();
dout.writeUTF(mesgsent);
dout.flush();
if(mesgsent.equals("kill")||mesgreceive.equals("kill"))
break;
}
din.close();
dout.close();
System.out.println("Closing the connection socket!");
s.close();
}
catch(Exception e)
{
System.out.println("There was an error in the program! " + e.getMessage());
}
}
}

Client.java:

import java.net.*;
import java.io.*;
import java.util.*;
public class Client 
{
public static void main(String[] args) {
try {
Socket clientsock=new Socket("localhost",8080);
DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
DataInputStream in =new DataInputStream(clientsock.getInputStream());
String receivemsg="",sendmesg="";
Scanner sc = new Scanner(System.in);
out.writeUTF("Client message: Welcome to Java tutorial with FirstCode!");
out.flush();
while(true)
{
receivemsg=in.readUTF();
System.out.println("Server Says: "+receivemsg);
System.out.println("Please enter your message");
sendmesg=sc.nextLine();
out.writeUTF(sendmesg);
out.flush();
if(receivemsg.equals("kill")||sendmesg.equals("kill"))
{
System.out.println("An interrupt occured in the conversation!");
break;
}
}
sc.close();
out.close();
in.close();
clientsock.close();
} catch (Exception e) {
System.out.println("An Error occured!");
System.out.println(e.getMessage());
} 
}
}

Output:

Server:
Server Starts! The presence of any errors will be found on the screen.
The client message: Welcome to Java tutorial with FirstCode!
Please enter your message:
Hello
Client Message: Hey man! What are you doing?
Please enter your message:
I’m learning Socket Programming in FirstCode.
Client Message: Oh Good, carry on.
Closing the connection socket!
Client:
Hello
Please enter your message:
Hey man! What are you doing?
Server says: I’m learning Socket Programming in FirstCode.
Oh Good, carry on.
An interrupt occurred in the conversation

Example of Java Socket Programming (Read – Write)

import java.net.*; 
import java.io.*; 
class FirstCodeServer{ 
public static void main(String args[])throws Exception{  
ServerSocket ss=new ServerSocket(3333);  
Socket s=ss.accept(); 
DataInputStream din=new DataInputStream(s.getInputStream());  
DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
String str="",str2="";  
while(!str.equals("stop")){  
str=din.readUTF(); 
System.out.println("client says: "+str);  
str2=br.readLine(); 
dout.writeUTF(str2); 
dout.flush();  
}  
din.close();  
s.close();  
ss.close();  
}}  

File: FirstCodeClient.java

import java.net.*; 
import java.io.*; 
class FirstCodeClient{ 
public static void main(String args[])throws Exception{  
Socket s=new Socket("localhost",3333);  
DataInputStream din=new DataInputStream(s.getInputStream());  
DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
String str="",str2="";  
while(!str.equals("stop")){  
str=br.readLine(); 
dout.writeUTF(str); 
dout.flush();  
str2=din.readUTF(); 
System.out.println("Server says: "+str2);  
}  
dout.close();  
s.close();  
}}  

Important points:

  • The Server application creates a ServerSocker on a certain port, here, it is 5000. This makes the server available for the client requests that arrive from port 5000.
  • The Server makes a new Socket to communicate with the client.
    socket = server.accept()
  • The presence of accept() method blocks and waits for the client to connect with the server.
  • Next, we take input from the socket using the getInputStream() method. This server is capable of receiving messages until the client sends the message “Over”.
  • Once the task is accomplished, we must close the connection by closing the socket and the input stream.
  • When we run both the Client and Server applications on our machine, we must compile both of them. We must run the server application first and run the client-server application next.

To run on Terminal or Command prompt:

1. Run the Server application:

$ java Server

Server started

Waiting for a client …

2. Run the Client application on another terminal as,

$ java Client

It will show – Connected and the server accepts the client and shows,

Client accepted

3. Now, we can type messages in the Client window. Sample input to the Client:

Hello
Learn Socket Programming in Java with FirstCode
Over
The Server simultaneously receives the message and displays it as:
Hello
Learn Socket Programming in Java with FirstCode
Over
Closing connection

When you use Eclipse, follow the steps given below:

1. Compile the Server and Client code in two different terminals or tabs.

2. Run the Server program first

3. Run the client program first

4. Type the messages in the Client window that is to be shown in the Server window simultaneously.

5. Type “Over” to end the process.

Conclusion

Now you can establish a client-server model using socket programming and make communication possible. I hope this article would have cleared all your nagging doubts about the socket programming concept in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *