Thursday, December 2, 2010

Basic Socket Programming


Socket programming a is data exchange method used in electrical systems, specially within two or more(even itself) systems within a network reachability.

Inter networked computers are widely using this method to transfer various data and information with remote systems.Socket programming, just up on the TCP layer, provides a mean of interprocess communication. In order to successful completion of the socket communication, all TCP/IP and lower layers need to be fully and correctly in functional.

As this articel involved in explaining simple simple data transfer implementation we will limit the limit our scope into computer application programming with its simplest form.

In order to exchange data within systems, there need to be at least two parties, who Requires some data to transfer to a Listener party. Who request to send data, or the one who initiate to connect is called the client. Who is ready to listen, and waiting for some one else to initiate a request is called server.

In order to start the communication, the server need to be ready and on listening state. So, at a glance lets look how to make a server and make it to listen for a client request.

Most of the languages provides easy way to create this object, while here i go with java.

A socket connection consists of a application layer's port and internet/IP layer's IP address.IP address belongs to the OS. So our application have no control over it.But we can use any[1-65535 (below 1024 need root access)] port[to listen].

According to the requirements we can use several implementation techniques to handle data transfered between a socket connection.It may be uni-directional, client server, multi thread server, transaction based,etc.

We may first go through basic implementation of a TCP listener or a listener socket.

For this article i use JDK 1.6 with NetBeans 6.9 on Ubunut 10.10 but codings are same for any java implementation (for same JDK).

File->New Project->Java(Categories)||Java Application(Application)->Project Name||Create Main Class->Finish

import Server Socket object.
import java.net.ServerSocket;

try {  
ServerSocket serverSocket = new ServerSocket(2000, 1);            
Socket clientSocket = serverSocket.accept();

//this part of the code will handle the business logic

        } catch (IOException ex){
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

Server socket will reserve a port number for the application process, which waits for a connection request from another process[local/remote].

'serverSocket.accept()'  will return a reference ('clientSocket') to the local end socket for the newly established data pipe.It can be used when ever the process wants to send or receive data back and forth.Initially the server process will run up to above line and hang there until a remote client send a request to connect.

Prepare another java project as above and implement a  client socket:

Socket socket = new Socket("localhost", 2000);
//business logic comes here
} catch (UnknownHostException unknownHostException) {
            System.out.println("Host no Found: " + unknownHostException.toString());
        } catch (IOException iOExceptionx) {
            System.out.println("Connection Failed: " + iOExceptionx.toString());
       } 
   }


Now, the connection can be established.But there is no use till we use it to send and receive data through the connection.So, create read and write iostreams on both socket ends.

on Server side:
InputStream receiveData = clientSocket.getInputStream();            
OutputStream sendData = clientSocket.getOutputStream();

on Client side:
InputStream receiveData = socket.getInputStream();            
OutputStream sendData = socket.getOutputStream();

Now  we can send and receive data through data channel between two processes.

Complete Code for Server:
package javaapplication1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/** 
* @author chand 
*/
public class Main {
/**
public static void main(String[] args) {
        try {
            // TODO code application logic here
            int maxDataSize = 100;
            String messageToSend = "messageFromServer";
            String receivedMessageFromClient = "";
            ServerSocket serverSocket = new ServerSocket(2000, 1);
            Socket clientSocket = serverSocket.accept();
            InputStream receiveData = clientSocket.getInputStream();
            OutputStream sendData = clientSocket.getOutputStream();

byte[] data = new byte[maxDataSize];
                      int receivedMessageLength = receiveData.read(data);
           receivedMessageFromClient = new String(data);
            System.out.println("\nReceivedMessageFromClient: " + receivedMessageFromClient                    + " messageLength: " + receivedMessageLength);

data = messageToSend.getBytes();
            sendData.write(data);

} catch (IOException iOExceptionx) {
           System.out.println("Connection Failed: " + iOExceptionx.toString());        }    
}
}

Complete Code for Client:

kage javaapplication2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* @author chand
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
int maxDataSize = 100;
String messageToSend = "messageFromClient";
String receivedMessageFromServer = "";
Socket socket = new Socket("localhost", 2000);
InputStream receiveData = socket.getInputStream();
OutputStream sendData = socket.getOutputStream();
byte[] data = new byte[maxDataSize];
//write and read events has been interchanged to avoid dead locks
data = messageToSend.getBytes();
sendData.write(data);
int receivedMessageLength = receiveData.read(data);
receivedMessageFromServer = new String(data);
System.out.println("\nReceivedMessageFromServer: " + receivedMessageFromServer
+ " messageLength: " + receivedMessageLength);
} catch (UnknownHostException unknownHostException) {
System.out.println("Host no Found: " + unknownHostException.toString());
} catch (IOException iOExceptionx) {
System.out.println("Connection Failed: " + iOExceptionx.toString());
}
}

No comments:

Post a Comment