Java Program 18 – Client Server Network Program

Program

Client Program

————————–

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

public class Server{

ServerSocket server=null;

public Server(){

    try{

        server=new ServerSocket(1001);
        processRequest();
        
    }catch(Exception e){System.out.println(e);}
    

}

public void processRequest(){

while(true){

        try{

            Socket client=server.accept();

            NewSocket Client=new NewSocket(client);

        }
        catch(Exception ee){System.out.println(ee);}

}
    

}
public static void main(String args[]){

    new Server();

}

}
class NewSocket extends Thread{

    Socket client=null;

public NewSocket(Socket socket){

    client=socket;

    start();
    }

public void run(){

    try
    {

        InputStream input=client.getInputStream();

        BufferedReader fromClient=new BufferedReader(new InputStreamReader(input));

        PrintWriter toClient=new PrintWriter(client.getOutputStream(),true);

        System.out.println(client);

        toClient.println("Enter First Number");

        int num1=Integer.parseInt(fromClient.readLine());

        System.out.println("Number 1 from Client  "+num1);

        toClient.println("Enter Second Number");

        int num2=Integer.parseInt(fromClient.readLine());

        System.out.println("Number 2 from Client  "+num2);

        toClient.println("Sum  "+(num1+num2));

}
catch(Exception e){
System.out.println(e);
}

}

}//end of New Thread

Server Program

————————–

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

public class Client{

    public static void main(String args[]){

    try{

    Socket client=new Socket("192.168.23.210",1001);

    BufferedReader fromServer=new BufferedReader(new InputStreamReader(client.getInputStream()));

    System.out.println(fromServer.readLine());
    
    BufferedReader fromConsole=new BufferedReader(new InputStreamReader(System.in));

    int num1=Integer.parseInt(fromConsole.readLine());

    PrintWriter toServer=new PrintWriter(client.getOutputStream(),true);
    toServer.println(num1);

    System.out.println(fromServer.readLine());

    int num2=Integer.parseInt(fromConsole.readLine());

    toServer.println(num2);

    System.out.println(fromServer.readLine());

    }catch(Exception e){
        System.out.println(e);
    }

    }
}


Output

Server Program
————————
D:\a5518\day10>javac Server.java

D:\a5518\day10>java Server
Socket[addr=/192.168.23.210,port=1722,localport=1001]
Number 1 from Client  10
Number 2 from Client  20

Client Program
———————–
D:\a5518\day10>javac Client.java

D:\a5518\day10>java Client
Enter First Number
10
Enter Second Number
20
Sum  30

D:\a5518\day10>


 

You can leave a response, or trackback from your own site.

Leave a Reply