Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

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.

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
public void connect(SocketAddress
1 This method connects the socket to the given input host.
host, int timeout) throws IOException
This method returns the port through which the socket is
2 public int getPort()
bound on the remote machine.
This method returns the port through which the socket is
3 public int getLocalPort()
bound on the local machine.
public SocketAddress
4 This method gives the address of the remote socket.
getRemoteSocketAddress()
public InputStream getInputStream()
5 This method returns the input stream of the socket.
throws IOException
public void close() throws This method closes the socket. Closing the socket makes it
7
IOException 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
This method returns the port on which the server socket is listening
1 public int getLocalPort()
to.
public Socket accept() throws It returns the socket and establishes a connection between the server
2
IOException and the client.
This method sets the time-out value for how long the server socket
3 public void setSoTimeout(int timeout)
has to wait for a client during the accept() method.
public void bind(SocketAddress host, This method binds the socket to the specified server and port in the
4
int backlog) 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:

1. Create a Socket
2. Connect it to ServerSocket by specifying the IP address and the port
number
3. Get the reference of the OutputStream
4. Attach this reference to OutputStreamWriter
5. Write and close
6. Get the reference of InputStream
7. Attach this reference to InputStreamWriter
8. Read and Buffer
9. Parse, interpret and process it
10.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:

1. Create ServerSocket
2. Bind it to a port number
3. Put it into the listening mode
4. Get the reference of InputStream
5. Attach the reference to InputStreamReader
6. Read and buffer
7. Parse the request
8. Prepare response
9. Get the reference of OutputStream
10.Attach the reference to OutputStreamReader
11. Write the response
12. 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:
Server started at port 5230
Waiting for a client … Commented [U1]:

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:
Connected

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.

You might also like