Socket Programming
1. What is socket? UDP and TCP differences
A socket is a mechanism for allowing communication between processes, be it programs running on the same
machine or different computers connected on a network. More specifically, Internet sockets provide a programming
interface to the network protocol stack that is managed by the operating system. Using this API, a programmer can
quickly initialise a socket and send messages without having to worry about issues such as packet framing or
transmission control. There are a number of different types of sockets available, but we are only really interested in
two specific Internet sockets. These are: • Stream sockets • Datagram sockets
What differentiates these two socket types is the transport protocol used for data transmission. A stream socket
uses the Transmission Control Protocol (TCP) for sending messages. TCP provides an ordered and reliable connection
between two hosts. This means that for every message sent, TCP guarantees that the message will arrive at the host
in the correct order. This is achieved at the transport layer so the programmer does not have to worry about this, it
is all done for you. A datagram socket uses the User Datagram Protocol (UDP) for sending messages. UDP is a much
simpler protocol as it does not provide any of the delivery guarantees that TCP does. Messages, called datagrams,
can be sent to another host without requiring any prior communication or a connection having been established. As
such, using UDP can lead to lost messages or messages being received out of order. It is assumed that the application
can tolerate an occasional lost message or that the application will handle the issue of retransmission. There are
advantages and disadvantages to using either protocol and it will be highly dependent on the application context.
For example, when transferring a file you want to ensure that, upon receipt, the file has not become corrupted. TCP
will handle all the error checking and guarantee that it will arrive as you sent it. On the other hand, imagine you are
sending 1000 messages detailing player position data every second in a computer game. The application will be able
to tolerate missing messages here so UDP would be more suitable.
Socket programming is a way of connecting two nodes on a network to communicate with each other. One
socket(node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection.
Server forms the listener socket while client reaches out to the server.
The communication that occurs between the client and the server must be reliable. That is, no data can be
dropped and it must arrive on the client side in the same order in which the server sent it.
TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet use
to communicate with each other. To communicate over TCP, a client program and a server program establish a
connection to one another. Each program binds a socket to its end of the connection. To communicate, the client
and the server each reads from and writes to the socket bound to the connection.
Addressing
Using Internet Sockets, we can identify a host using an IP address and a port number. The IP address uniquely
identifies a machine while the port number identifies the application we want to contact at that machine. There are
a range of well known port numbers, such as port 80 for HTTP, in the range 0 - 1023. When choosing port numbers,
anything above the well know port number range should be fine, but you cannot guarantee that another application
will not be already using it.
5. socket features - how it works
Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server
just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running and the port
number on which the server is listening. To make a connection request, the client tries to rendezvous with the server
on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port
number that it will use during this connection. This is usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to
the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket
so that it can continue to listen to the original socket for connection requests while tending to the needs of the
connected client.
On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to
communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
6. Java Socket Programming
Java provides a collection of classes and interfaces that take care of low-level
communication details between the client and the server.
These are mostly contained in the [Link] package, so we need to make the following
import:
import [Link].*;
We also need the [Link] package which gives us input and output streams to write to
and read from while communicating:
import [Link].*;
[Link] package
Socket Class methods are found in Java. A socket is bound to be a port number so that
the TCP recognizes the port number in which the data is to be sent. Java provides a set of
classes one of which is [Link]. This is used for the fast development of network applications.
Key classes, interfaces, and exceptions that are present in [Link] package simplify the
complexity involved in creating client and server programs
The [Link] class represents the socket that both the client and the server use to
communicate with each other. The client obtains a Socket object by instantiating one, whereas
the server obtains a Socket object from the return value of the accept() method.
More Info:
[Link]
et/[Link]
The [Link] class is used by server applications to obtain a port and listen for
client requests
More
Info:[Link]
va/net/[Link]
The following steps occur when establishing a TCP connection between two computers using
sockets −
1. The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
2. The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
3. After the server is waiting, a client instantiates a Socket object, specifying the server
name and the port number to connect to.
4. The constructor of the Socket class attempts to connect the client to the specified server
and the port number. If communication is established, the client now has a Socket
object capable of communicating with the server.
5. On the server side, the accept() method returns a reference to a new socket on the
server that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream
Simple Server side socket program:
import [Link].*;
import [Link].*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=[Link]();//establishes connection
DataInputStream dis=new DataInputStream([Link]());
String str=(String)[Link]();
[Link]("message= "+str);
[Link]();
}catch(Exception e){[Link](e);}
}
}
Simple program for the client
import [Link].*;
import [Link].*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream([Link]());
[Link]("Hello Server");
[Link]();
[Link]();
[Link]();
}catch(Exception e){[Link](e);}
}
}
Task 1
Create a one-way Client and Server setup where a Client connects, sends messages to server and the
server shows them using TCP-based socket connection.
Server Side
//A Java program for a Server
import [Link].*;
import [Link].*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
[Link]("Server started");
[Link]("Waiting for a client ...");
socket = [Link]();
[Link]("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream([Link]()));
String line = "";
// reads message from client until "Over" is sent
while ()
{
try
{
line = [Link]();
[Link](line);
}
catch(IOException i)
{
[Link](i);
}
}
[Link]("Closing connection");
// close connection
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}
Client Side
// A Java program for a Client
import [Link].*;
import [Link].*;
public class Client
{
// 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
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
[Link]("Connected");
// takes input from terminal
input = new DataInputStream([Link]);
// sends output to the socket
out = new DataOutputStream([Link]());
}
catch(UnknownHostException u)
{
[Link](u);
}
catch(IOException i)
{
[Link](i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while ()
{
try
{
line = [Link]();
[Link](line);
}
catch(IOException i)
{
[Link](i);
}
}
// close the connection
try
{
[Link]();
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}
public static void main(String args[])
{
Client client = new Client("[Link]", 5000);
}
}
UDP-based Communication
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP instead of TCP
Import Classes :
Java DatagramSocket class
Java DatagramPacket Class :
Server- Side
Create a DatagramSocket object. Just as for the creation of a ServerSocket object, this means
supplying the object's constructor with the port number.
For example:
DatagramSocket datagramSocket =new DatagramSocket(1234);
Create a array byte for incoming datagrams. This is achieved by creating an array of bytes
For example:
byte[] arr = new byte[256];
Create a DatagramPacket object for the incoming datagrams.
The constructor for this object requires two arguments:
• the previously-created byte array;
• the size of this array.
For example:
DatagramPacket inPacket = new DatagramPacket(arr, [Link]);
Accept an incoming datagram. This is effected via the receive
method of our DatagramSocket object, using our
DatagramPacket object as the receptacle.
For example:
[Link](inPacket);
Accept the sender's address and port from the packet.
Methods getAddress and getPort of our DatagramPacket object
are used for this.
For example:
InetAddress clientAddress = [Link]();
int clientPort = [Link]();
Retrieve the data from the [Link] convenience of handling,
the data will be retrieved as a string, using an overloaded form of
the String constructor that takes three arguments:
• a byte array;
• the start position within the array (= 0 here);
• the number of bytes (= full size of array here).
For example:
String message = new String([Link](), 0,[Link]());
Create the response datagram.
Create a DatagramPacket object,:
The first of these arguments is returned by the getBytes method
of the String class (acting on the desired String response).
For example:
DatagramPacket outPacket =
new DatagramPacket([Link](),
[Link](),clientAddress, clientPort);
Send the response [Link] is achieved by calling method send of our DatagramSocket
object, supplying our outgoing DatagramPacket object as an argument.
For example:
[Link](outPacket);
[Link]();
Client-side
1. Create a DatagramSocket object.
This is similar to the creation of a DatagramSocket object in the server program, but
with the important difference that the constructor here requires no argument, since a
default port (at the client end) will be used.
For example:
DatagramSocket datagramSocket = new DatagramSocket();
2. Create the outgoing datagram.
This step is exactly as for step 7 of the server program. For example:
DatagramPacket outPacket =
new DatagramPacket([Link](),
[Link](), host, PORT);
[Link](outPacket);
4. Create a buffer for incoming datagrams.
For example:
byte[] buffer = new byte[256];
5. Create a DatagramPacket object for the incoming datagrams.
For example:
DatagramPacket inPacket =
new DatagramPacket(buffer, [Link]);
6. Accept an incoming datagram.
For example:
[Link](inPacket);
7. Retrieve the data from the buffer.
. For example:
String response =new String([Link](),0,
[Link]());
8. Close the DatagramSocket.
For example:[Link]();
References
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
m
[Link]
[Link]
[Link]