0

I want to develop a program that deals with multiple clients. people should be able to have 2 options at the beginning of program. they should be able to either:

  1. To wait for someone to choose them to do some stuff*(I have no problem with that stuff)*
  2. To choose from the people waiting.

Once a client chooses someone from waiting list their part of program should start running. and other people of group 1 should still wait. my problem is I don't know how to do so. I believe I should make different ports so that our server can listen to different clients and response only to those that are joined together.

The problem is, if I change the port of server how can I let others using the old port to continue and still listen to them? i tried something like below in server

while (true) {
            port=p.getPort();//this gives us an empty port everytime
            //we call it(it's from an array in a class i made)
            listener = new ServerSocket(port);
            new Handler(listener.accept()).start();
        }

The problem is once we change the port of server it kills other ports also how can tell the server when to listen to each port. I'm so confused and if anyone can help me I be grateful

Saleh Parsa
  • 1,415
  • 13
  • 22

1 Answers1

1

You don't need to change the port everytime - multiple connections can happen on the same port (How do multiple clients connect simultaneously to one port, say 80, on a server?).

Usually to accept an indefinite amount of clients you need to create a new thread which will loop over the accept function (https://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#accept()) which returns a socket which enables you to have a communication with this client. You can then start a new thread with this specific client socket and listen to whatever you want.

It could go like this (not real implementation) :

serverSocket = new ServerSocket(port);
thread = new Thread(listeningFunc);
thread.start()

listeningFunc() {
    while(true) {
        newClientSocket = serverSocket.accept() // This blocks the thread until a client connects
        clientThread = Thread(new ListenClient(newClientSocket)); // A new thread is created for each new clients
        clientThread.start()
    }
}

ListenClient implements Runnable {
    public ListenClient(Socket clientSocket) {
        //Constructor
    }

    @Override // Override run function which is called on thread start
    public void run() {
        // Wait for interactions from the client
    }
}

Hope this helps

Olivier Samson
  • 609
  • 4
  • 13