Saturday 4 August 2012

Socket Programming

What is Socket ?
==========================
A socket is one endpoint of a two-way communication link between two programs running generally on a network. A socket is a bi-directional communication channel between hosts (a computer on a network often termed as host).
As file is an abstraction of hard drive. Similarly we can think of a socket as an abstraction of the network.  Each end has input stream (to send data) and output stream (to receive data) wired up to the other host.
We store and retrieve data through files from hard drive, without knowing the actual mechanism of the hard drive. Similarly here we send and receive data to and from network through socket, without actually going into underlying mechanics. 
In earlier post "Concept of Streams" we had seen that, we read and write data from/to a file using streams. To read and write data to socket, we will also use streams.
What is Port ?
==========================
It is a transport address to which processes can listen for connections request. There are different protocols available to communicate such as TCP and UDP. There are 64k ports available for TCP sockets and 64k ports available for UDP, so at least theoretically we can open 128k simultaneous connections. There are well-known ports which are below 1024 and provides standard services. Some well-known ports are:
  • FTP works on port 21
  • HTTP works on port 80
  • TELNET works on port 23 etc.
How Client – Server Communicate ?
==========================
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 to which the server is connected.
As soon as client creates a socket that socket attempts to connect to the specified server. The server listens through a special kind of socket, which is named as server socket. The sole purpose of the server socket is to listen for incoming request; it is not used for communication. If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket, a communication socket, bound to a different port number. The server needs a new socket (and consequently a different port number) so that it can continue to listen through the original server socket for connection requests while tending to the needs of the connected client. This scheme is helpful when two or more clients try to connect to a server simultaneously (a very common scenario).
On the server side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. Note that the socket on the client side is not bound to the port number used to make contact with the server. Rather, the client is assigned a port number local to the machine on which the client is running.  The client and server can now communicate by writing to or reading from their sockets.
Steps – To Make a Simple Client
==========================

1)Import required package
java.net.*;
java.io.*; 
2) Connect / Open a Socket with Server
Create a client socket (communication socket)
Socket s = new Socket(“serverName”, serverPort) ; 
serverName: Name or address of the server we wanted to connect such  as http://www.google.com  or 172.2.4.98 etc.


Note:- For testing if we can run client and server on the same machine then specify “localhost” as the name of server.
serverPort : Port number to which we want to connect .
3) Get I/O Streams of Socket
Get input & output streams connected to the socket. For reading data from socket a socket has input stream attached to it.
InputStream is = s.getInputStream();
/* to convert byte oriented stream into char oriented 
 buffered reader we use intermediary stream that helps in achieving this purpose*/
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);  
For writing data to socket, a socket has also output stream attached to it. Therefore,
OutputStream os = s.getOutputStream(); 
/* to convert byte oriented stream into character oriented print writer here we will not use any intermediary stream because PrintWriter constructor directly accepts an object of OutputStream */
PrintWriter pw = new PrintWriter(os, true);  
Here notice that true is also passed to so that output buffer will flush.
4) Send / Receive Message
Once you have the streams, sending or receiving messages isn’t a big task. It’s very much similar to the way as in files. To send messages:
pw.println(“hello world”);   
To read messages:
String recMsg = br.readLine(); 
5) Close Socket
s.close();
Steps – To Make a Simple Server
==========================
1) Import similar set of packages
2) Create a Server Socket
In order to create a server socket, we will need to specify port no. eventually on which server will listen for client requests. 
ServerSocket ss = new ServerSocket(serverPort) ;
serverPort: port local to the server i.e. a free port on the server machine. This    is the same port number that is given in the client socket constructor.
3) Wait for Incoming Connections
The job of the server socket is to listen for the incoming connections. This listening part is done through the accept method. 
Socket s = ss.accept();
The server program blocks at the accept method and waits for the incoming client connection. When a request for connection comes it opens a new communication socket (s) and use this socket to communicate with the client.
4) Get I/O Streams of Socket
Once we have the communication socket, getting I/O streams from communication socket is similar to the way we did in making a client. For reading data from socket:
InputStream is = s.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);  
For writing data to socket:
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os, true); 
5) Send / Receive Message
Sending and receiving messages is very similar as in making of client. To send messages:
pw.println(“hello world”); 
To read messages
String recMsg = br.readLine(); 
6) Close Socket
s.close();





No comments:

Post a Comment