简体   繁体   中英

Writing java server to handle simultaneous client responses

I'm in a group that is building a 4 player multiplayer game, and I'm developing the guts of the server using sockets. I've currently set up the server to take multiple client connections, and save them to an array of sockets to be accessed when I need to write to a specific client.

I know how to handle a single response from a single client:

String response; while((response = in.readLine()) != null) {//do something}

but how do I manage two responses that will be sent to the server at the same time?

Using THREADs. There's also an example in the docs.. Also see the related question to the right side ---->

https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

Supporting Multiple Clients

To keep the KnockKnockServer example simple, we designed it to listen for and handle a single connection request. However, multiple client requests can come into the same port and, consequently, into the same ServerSocket. Client connection requests are queued at the port, so the server must accept the connections sequentially. However, the server can service them simultaneously through the use of threads—one thread per each client connection.

The basic flow of logic in such a server is this:

 while (true) { accept a connection; create a thread to deal with the client; } 

The thread reads from and writes to the client connection as necessary.

I think you need something like this:

someMethod() {

    // Your array of sockets
    Socket[] clientSockets;

    // Create a new Thread to handle each socket and start them
    for (int i = 0 ; i < clientSockets.length ; ++i) {
        Thread t = new ListenToClientThread(clientSockets[i]);
        t.start();
    }
}

// When you call start() on a Thread it calls run()
class ListenToClientThread extends Thread {
    private Socket socket;

    ListenToClientThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        PrintWriter out =
            new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));

        String response;
        while((response = in.readLine()) != null) {//do something}
    }
}

The trick here is handling all the responses in a way that allows all the different threads to access shared objects and for this you'll have to read all about synchronisation and beware ...there are dragons!

instead of while on a single input, loop through all your inputs and readline them.

just implement socketObject.readline() or similar.

for (Thread thread : threads)
    {
         thread.read()
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM