Socket Programming
Socket helps in communication. It works on both, CLI and GUI. The notion of a socket allows a single
computer to serve many different clients at once, as well as serving many different types of information.
A server is anything that has some resources that can be shared. A client is simply any
other entity that wants to gain access to a particular server.
Internet Protocol(IP) is a low-level routing protocol that breaks data into smaller packets and
send them to an address across a network, which does not gurantee to deliver said packets to the destination.
Socket communicate with the help of IP address and port number. Port is a numbered socket on a
particular machine. A server process is said to listen to a port until a client connects to it. A server
is allowed to accept multiple clients connected to the same port number, althogh each session is unique.
To manage multiple client connections, a server process must be multithreaded or have some other means of
multiplexing the simultaneous I/O.
Port numbercan be reserved or non-reserved. Some examples of reserved ports includes FTP of 21 (connection
oriented), HTTP of 80 (connectionless), Telnet of 23 (connection oriented). From, 1-1024,is called reserved
port and from 1025-65355, it is called non-reserved port. These ports are created by us. We can use our own
services which is not occupied by any other.
Communication Protocol
TCP(Transmission Control Protocol) is a connection oriented protocol which is reliable. It uses
handshake methodology. In this, packets are sent from source to destination. After receiving the packets,
the destination sends acknowledgement to source so that source stops sending i.e. source is notified that
destination has received the data. Mobile calling system uses TCP protocol because when we call, we can
hear the caller tune which means that call has reached the destination.
TCP also ensure that not a single packets can be missed. In banking transaction, not a single packet should
be missed, otherwise transaction fails, therefore, it uses TCP. The disadvantage of TCP is that if there
are many destinations, then each destination sends acknowledgement to source. Therefore, data gets flooded.
Thus, TCP is not used for large amount of data.
UDP(User Datagram Protocol) is a connectionless protocol which is not reliable. Here, source is not
notified whether the packets has reached the destination or not. Mobile SMS system uses this protocol because
when we send message, we are not notified whether the SMS is received or not(We are talking about earlier
days, nowadays we are notified). In UDP, packets can be missed. While watching online movies, if one second
is missed, there is no much affection. Therefore, it uses UDP. UDP is suitable when large amount of data
is involved.
Classes of TCP
A Socket can be used to connect java's I/O system to other programs that may reside either on the local
machine or on any other machine on the Internet. These classes belongs to java.net package.
For Server
ServerSocket class is used for creating server and its services for server side. It waits for the
clien before doing anything.
ServerSocket ss=new ServerSocket(<port-no.>);
Here, ss is the object created for ServerSocket. Once, its object is created and port no. is passed as an argument, it is ready for accepting client request on
this port number. We can say that service started.
Socket class is used for data transfer i.e. it is designed to connect to server sockets and initialize
protocol exchanges.
Socket sc=new Socket();
Here sc is the object created for Socket. The creation of a socket object implicitly establishes a connection
between the client and the server.
sc=ss.accept();
To establish link with the client, accept() is used.
sc.getInputStream() - Reading data from socket.
sc.getOutputStream() - Writing data on socket.
For Client
Socket sc=new Socket(<IP address or name>,<port-no.>);
Here, socket class is not referential. It takes two arguments, IP address or name and port number. It takes
two arguments, IP address or name and port number. If IP address has been used, then another is needed to
be used. Therefore, we use the name directly. If connection is to be established to own system, then
localhost is written in first argument. After this, connection is established.
sc.getOutputStream() and sc.getInputStream()
Here also, these two methods are used for writing and reading purposes respectively.
For server:
import java.net.*;
import java.io.*;
public class tcpserver
{
public void server()
{
ServerSocket ss=null;
Socket sc=null;
BufferedReader br=null;
PrintWriter pw=null;
BufferedReader sbr=null;
try
{
ss=new ServerSocket(8888);
sc=new Socket();
sc=ss.accept();
pw=new PrintWriter(sc.getOutputStream(),true);
br=new BufferedReader(new InputStreamReader(System.in));
sbr=new BufferedReader(new InputStreamReader(sc.getInputStream()));
String s1;
while((s1=sbr.readLine())!=null)
{
System.out.println("Client says "+s1);
pw.println(br.readLine());
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
finally
{
try
{
pw.close();
sc.close();
ss.close();
sbr.close();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
public static void main(String[] arg)throws Exception
{
tcpserver ob=new tcpserver();
ob.server();
}
}
Now compile this program
For Client:
import java.net.*;
import java.io.*;
public class tcpclient
{
public void client()
{
Socket sc=null;
BufferedReader br=null;
PrintWriter pw=null;
BufferedReader sbr=null;
try
{
sc=new Socket("localhost",8888);
pw=new PrintWriter(sc.getOutputStream(),true);
br=new BufferedReader(new InputStreamReader(System.in));
sbr=new BufferedReader(new InputStreamReader(sc.getInputStream()));
String s1;
while((s1=br.readLine())!=null)
{
pw.println(s1);
System.out.println("Server says "+sbr.readLine());
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
finally
{
try
{
pw.close();
sc.close();
sbr.close();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
public static void main(String[] arg)throws Exception
{
tcpclient ob=new tcpclient();
ob.client();
}
}
Now, compile this program on second instance of command prompt.
Then, run both the programs and start chating.
E:\java\java>java tcpserver
Client says Hello
Hii
Client says bye
bye
E:\java\java>java tcpclient
Hello
Server says Hii
bye
Server says bye
Datagrams
Datagrams are bundles of information passes between machines. Once the datagram has been released ti its intended target,
there is no assurance that it will arrive or even that someone will be there to catch it. Therefore,
when the datagram is received, there is no assurance that it hasn't been damaged in transit or that
whoever sent it is still there to receive a response.
Classes of UDP
It uses two classes:
DatagramSocket and
DatagramPacket. The classes of UDP belongs to
java.net package. The DatagramPacket is the mechanism used to send or receive the DatagramPacket.
While receiving, the constructor of DatagramPacket accepts two parameters i.e. the data, the length
of data, the IP address of the receiver and port number.
InetAddress is a class which is used
to find the IP address of any incoming packet and store it.
getAddress() is used to get the
destination address which is used for sending.
getPort() is used to find the port number of
sender packet.
For Server:-
import java.io.*;
import java.net.*;
public class udpserver
{
public void server()
{
DatagramSocket ds=null;
try
{
ds=new DatagramSocket(9888);
while(true)
{
byte[] b=new byte[100];
DatagramPacket rdp=new DatagramPacket(b,b.length);
ds.receive(rdp);
String s=new String(rdp.getData());
System.out.println("Client says "+s);
InetAddress inet=rdp.getAddress();
int port=rdp.getPort();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1=br.readLine();
byte[] b1=s1.getBytes();
DatagramPacket sdp=new DatagramPacket(b1,b1.length,inet,port);
ds.send(sdp);
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
finally
{
try
{
ds.close();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
public static void main(String[] arg)throws Exception
{
udpserver ob=new udpserver();
ob.server();
}
}
Now, Compile the program.
For Client:
import java.io.*;
import java.net.*;
public class udpclient
{
public void client()
{
DatagramSocket ds=null;
try
{
ds=new DatagramSocket();
while(true)
{
InetAddress inet=InetAddress.getByName("localhost");
int port=9888;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
byte[] b=s.getBytes();
DatagramPacket dp=new DatagramPacket(b,b.length,inet,port);
ds.send(dp);
byte[] b1=new byte[100];
DatagramPacket rdp=new DatagramPacket(b,b.length);
ds.receive(rdp);
String s1=new String(rdp.getData());
System.out.println("Server says "+s1);
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
finally
{
try
{
ds.close();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
public static void main(String[] arg)throws Exception
{
udpclient ob=new udpclient();
ob.client();
}
}
Now, compile this program on second instance of command prompt.
Then, run both the programs and start chating.
E:\java\java>java udpserver
Client says hii
bye
Client says bye
E:\java\java>java udpclient
hii
Server says bye
bye