Friday, September 13, 2013

Networking : Lesson 01 – Socket Programming


Networking : Lesson 01 – Socket Programming

Networking is a concept of connecting two or more computing devices together.
The java.net package of the J2SE APIs contains a collection of classes and Interfaces.

What is a Protocol ?

A Protocol is a set of rules that is followed for communication.
Examples – FTP, TCP, SMTP, Telnet, POP, etc.

Socket Programming
Sockets provide the communication mechanism between two computers using TCP.

A client program creates a socket on its end and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket.

java.net.Socket class - represents a socket
java.net.ServerSocket class - provides a mechanism for the server program to listen for clients and establish connections with them.

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 port number to connect to.
4. The constructor of the Socket class attempts to connect the client to the specified server and 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.

TCP is a two-way communication protocol, so data can be sent across both streams at the same time.


Example 1 – Client / Server communication

package Networking;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientServerExecute {

       /**
       * @param args
       */
       public static void main(String[] args) {

              ClientServerExecute execute = new ClientServerExecute();
              execute.doExecute();
       }

       private void doExecute(){

              Thread threadServer = new Thread(){
                      public void run(){
                             executeServer();
                      }
              };

              Thread threadClient = new Thread(){
                     public void run(){
                             executeClient();
                     }
              };

              threadServer.start();
              threadClient.start();
      }

      private void executeServer(){

              try {
                     ServerSocket serverSocket = new ServerSocket(6666);
                     System.out.println("[Server] Create new socket");

                     //Establish the connection
                     Socket socket = serverSocket.accept();
                     System.out.println("[Server] Establish the connection");

                     DataInputStream dIs = new DataInputStream(socket.getInputStream());
                     System.out.println("[Server] Get data Input stream");

                     String string = (String)dIs.readUTF();
                     System.out.println("[Server] Read the Input stream --> " + string);

                     serverSocket.close();
                     System.out.println("[Server] Close Server socket");
              } catch (IOException e) {
                     e.printStackTrace();
              }
      }

      private void executeClient(){

              try {
                      //Establish the connection
                      Socket socket = new Socket("localhost",6666);
                      System.out.println("[Client] Establish the connection"); 

                      DataOutputStream dOutStrm = new DataOutputStream(socket.getOutputStream());
                      System.out.println("[Client] Create Output Stream Object");

                      dOutStrm.writeUTF("Hello Server");
                      System.out.println("[Client] write Out put stream");
                      dOutStrm.flush();
                      System.out.println("[Client] flush");

                      dOutStrm.close();
                      socket.close();
                      System.out.println("[Client] close");
               } catch (IOException e) {
                      e.printStackTrace();
               }
       }
}


Output as follows :

[Server] Create new socket
[Server] Establish the connection
[Server] Get data Input stream
[Client] Establish the connection
[Client] Create Output Stream Object
[Client] write Out put stream
[Client] flush
[Client] close
[Server] Read the Input stream --> Hello Server
[Server] Close Server socket