Client Server Communication - TCP / IP Sockets



// Socket Programing
// Client Server Communication
// Server Program

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

public class Server
{
     Server()
     {
     }   
    
     public void run() throws IOException
     {
        try
          {
              // Creating Server Socket
              ServerSocket ss = new ServerSocket(1500,10);
             
              // Accepting Connection from Client at port 1500
              Socket conc = ss.accept();
                                     
              ObjectOutputStream out = new ObjectOutputStream(conc.getOutputStream());
              ObjectInputStream in = new ObjectInputStream(conc.getInputStream());
             
              // Reading data from client
              String Name = (String)in.readObject();
             
              // Creating response
              Date dt = new Date();
              String res = "Welcome " + Name + "\n";
               res = res.concat("Current date and time is " + dt);
             
              // Sending response
              out.writeObject(res);
          }                 
          catch(Exception e)
          {  
          }
          finally
          {
              in.close();
              out.close();
              ss.close();
          }
    }
    
    public static void main(String args[]) throws IOException
     {
        Server s = new Server();
          s.run();
     }
}






// Socket Programing
// Client Server Communication
// Client Program

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

public class Client
{  
     Client()
     {
     }

     public void run() throws IOException
     {
        try
          {
              // Creating Client socket at port 1500
              Socket cs = new Socket("localhost",1500);
         
              ObjectOutputStream out = new ObjectOutputStream(cs.getOutputStream());
              ObjectInputStream in = new ObjectInputStream(cs.getInputStream());
           
              // Reading input from Client and sending to Server
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.print("Enter name : ");
              String Name = br.readLine().trim();
              out.writeObject(Name);
             
              // Reading and displaying response from server
              String res = (String)in.readObject();
              System.out.println(res);                          
          }            
          catch(Exception e)
          {
          }
          finally
          {       
              in.close();
              out.close();
              cs.close();
          }
     }

     public static void main(String args[]) throws IOException
     {
          Client c = new Client();
          c.run();
     }
}




















No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu