Client Server Interaction Java

Thursday, 25 September 2014

java logo

 

At starting point you have to program two sides of this program

one part is of Server and another is client.

So lets Get Started

This one is for Server End place in on static or in jbuttonAction Performed

 

try
{
       ServerSocket serverSocket = new ServerSocket(8080);
       while(!serverSocket.isClosed())
       {
           Socket socket = serverSocket.accept();
           PrintWriter writer = new PrintWriter(socket.getOutputStream());
           String advice = “here is your message to send to client”
           System.out.println("Sending advice: " + advice);
           writer.write(advice);
           writer.close();
           System.out.println("Advice sent!");
           socket.close();
}
}
catch(Exception e)
{
       System.out.println(e.getMessage());
}

That’s it Now for Client Side

try
{
        System.out.println("Getting some good advice...");
        Socket socket = new Socket("localhost", 8080);
       BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String advice = reader.readLine();
        jTextArea2.setText(advice);
        reader.close();
        socket.close();
}
catch(Exception e)
{
         System.out.print("Whoops! It didn't work!\n");
}

Here it goes Now run the server Code First and then the Client Code Thats it.