Wednesday, 7 August 2013

Basic Client-Server Programming and A Simple Chat Program With Client/Server:

Basic Client-Server Programming 

Simple TCP/IP programming in java

TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.

Socket Programming: This is most widely used concept in Networking and it has been explained in very detail.

Socket:A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

The java.net package in the Java platform provides a class, Socket, that implements one side of a two-way connection between your Java program and another program 
The package includes ServerSocket class, which implements a socket that servers can use to listen for and accept connections to clients. This lesson shows you how to use the Socket and ServerSocket classes.

Hosts have ports, numbered from 0-65535. Servers listen on a port. Some port numbers are reserved so you can't use them when you write your own server. 

How to find an available port?

ServerSocket s = new ServerSocket(0);
System.out.println("listening on port: " + s.getLocalPort());
 

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.

When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has its remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection. 

Gets the socket's input and output stream and opens readers and writers on them.
Initiates communication with the client by writing to the socket (shown in bold).
Communicates with the client by reading from and writing to the socket.

import java.io.*;
import java.net.*;

class TCPServer
{
   public static void main(String argv[]) throws Exception
      {
         String clientSentence;
         String capitalizedSentence;
         ServerSocket welcomeSocket = new ServerSocket(49596);

         while(true)
         {
            Socket connectionSocket = welcomeSocket.accept();

            BufferedReader inFromClient =
               new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            DataOutputStream outToClient = new         DataOutputStream(connectionSocket.getOutputStream());

            clientSentence = inFromClient.readLine();

            System.out.println("Received: " + clientSentence);

            capitalizedSentence = clientSentence.toUpperCase() + '\n';

            outToClient.writeBytes(capitalizedSentence);
         }
      }
}
Client program: Server should already be running and listening to the port, waiting for a client to request a connection. So, the first thing the client program does is to open a socket that is connected to the server running on the hostname and port specified:


  Socket clientSocket = new Socket("localhost",49596);

The server's socket and the client's socket are connected.

The communication between the client and the server. The client speaks first, so the server must listen first. The server does this by reading from the input stream attached to the socket.
import java.io.*;

import java.net.*;

class TCPClient

{

 public static void main(String argv[]) throws Exception

 {

  String sentence;

  String modifiedSentence;

  Socket clientSocket = new Socket("localhost",49596);

 

  System.out.println("Enter lines of text.");

  System.out.println("Enter 'stop' to quit.");

  do {

      BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));

      DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

      BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

  sentence = inFromUser.readLine();

 outToServer.writeBytes(sentence + '\n');

  modifiedSentence = inFromServer.readLine();

  System.out.println("FROM SERVER: " + modifiedSentence);

  } while(!sentence.equals("stop"));

  clientSocket.close();

  }

 }
If the client doesn't want to speak, it says "stop." and the client exits the loop.socket connection is closed.

Output:
Execute Server and Client programs on two different command prompts.

First execute Server 



Client


                                                                Response in Server:

Response in Client:
                                                  

A Simple Chat Program With Client/Server:

Server Program:

  
import java.io.*;
    import java.net.*;
    public class TCPServerChat
    {
    public static void main(String a[])throws IOException
    {
    try
    {
    ServerSocket s=new ServerSocket(49596);
    System.out.println("Server Waiting For The Client");
    Socket cs=s.accept();
    InetAddress ia=cs.getInetAddress();
    String cli=ia.getHostAddress();
    System.out.println("Connected to the client with IP:"+cli);
    BufferedReader in=new BufferedReader(new
    InputStreamReader(cs.getInputStream()));
    PrintWriter out=new PrintWriter(cs.getOutputStream(),true);
    do
    {
    BufferedReader din=new BufferedReader(new
    InputStreamReader(System.in));
    System.out.print("To Client:");
    String tocl=din.readLine();
    out.println(tocl);
    String st=in.readLine();
    if(st.equalsIgnoreCase("Bye")||st==null)break;
    System.out.println("From Client:"+st);
    }while(true);
    in.close();
    out.close();
    cs.close();
    }
    catch(IOException e) { }
    }
    }
Client Program:

   
import java.io.*;
    import java.net.*;
    public class TCPClientChat
    {
    public static void main(String a[])throws IOException
    {
    try
    {
    Socket con=new Socket(" 192.0.0.1",49596);
    BufferedReader in=new BufferedReader(new
    InputStreamReader(con.getInputStream()));
    PrintWriter out=new PrintWriter(con.getOutputStream(),true);
    while(true)
    {
    String s1=in.readLine();
    System.out.println("From Server:"+s1);
    System.out.print("Enter the messages to the server:");
    BufferedReader din=new BufferedReader(new
    InputStreamReader(System.in));
    String st=din.readLine();
    out.println(st);
    if(st.equalsIgnoreCase("Bye")||st==null)break;
    }
    in.close();
    out.close();
    con.close();
    }
    catch(UnknownHostException e){ }
    }
    }
In the place of 192.0.0.1 we should place the client IP-address and execution procedure is same as above one. 



1 comment:

praveen said...

its very help ful for us