Sanjay Chada
Sanjay Chada

Reputation: 11

How to create a Java server which listens to a port and accepts multiple clients

I need to develop a Java server which listens on a port on my pc.

Multiple clients (on the same PC) will access that port and the server should invoke a common method (for all clients, like file copying) which I have written in another class.

My input would be a file path through command line from each client on to that port. It should invoke a thread each time a client accesses the port.

Upvotes: 0

Views: 182

Answers (1)

Vipul
Vipul

Reputation: 41

You can use the server socket class from the java.net package for creating a socket which will listen to incoming client connections on that port. On accepting new connections, start a new thread specific to that client which will handle that client while the server can continue to listen for new connections . Put the common method which you want the server to invoke in the run() method of the new thread.

public class server {

public static void main (String[] args) 
{
    ServerSocket sock = new ServerSocket (6666); // Server Socket which will listen for connections 
    try{
        while(true)
        {
            new clientThread(sock.accept()).start(); // start a new thread for that client whenever a new request comes in  
        }
    }
    catch (IOException ioe)
    {
         ioe.printStackTrace();
    }
    finally {
        sock.close();
    }
}

// Client Thread for handling client requests
private static class clientThread extends Thread {

    Socket socket ;
    BufferedReader in ;
    PrintWriter out;

    clientThread(Socket socket) throws IOException
    {
        this.socket = socket ;
    }

    public void run()
    {
         try 
        {
             // create streams to read and write data from the socket
             in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
             out = new PrintWriter(socket.getOutputStream(), true);

           // put your server logic code here like reading from and writing to the socket
        } 
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         finally {
              try {
                    socket.close();
                } catch (IOException ioe) {
                     ioe.printStackTrace();
                }
         }
    }   
}

}

You can refer to the documentation for further information about the java socket API All About Sockets - Oracle

Upvotes: 3

Related Questions