Monday, 27 March 2017

Creating a Simple Server- Client Connection in JAVA


The Client can connect to the Server with the same Socket by which the Server is Connected. Now the Server and Client can Communicate by reading and writing from the Socket. Communication is done by TCP(Transmission Control Protocol).

Example:

impot java.io.*;
//First the Server side

class ServerSide{
public static void main (String args[])
    {
       ServerSocket serverSocket = new ServerSocket(Port_number);
       System.out.println("SERVER STARTED");
       Socket s = ss.accept();
       System.out.println("CLIENT CONNECTED");
    }
}

//Now the Client Side

import java.net.*;

class Client {

public static void main(Sring args[])
    {
      Socket s= new Socket("localhost", Port_number);
      //Port no.should be same as the Server Port Number.
    }
 
}

Explanation:
So, the Client will connect to the Server Only when the Client class will execute. And One more thing make different java files for both. One for Client and one for Server.

No comments:

Post a Comment