Question

We are making an somewhat RTS networked game in java. i have this main server that accepts other players which has the serversocket. Then on our game when you created your own game room i filtered all the players that has joined my room.then when the game starts the creator of the room should be the host. should i be still using my main server or should i establish a new serversocket for those who are connected to my room? and 1 more thing should a inputstream.readObject() what for an message to go for another loop?or it continuously looping? here is the sample code snippet for the inputstream.

 public void run() {
    while (running) {
        try {
            inStream = new ObjectInputStream(client.getInputStream());
            command = (String) inStream.readObject();

            Thread.sleep(10);
        }//try
        catch (Exception e) {
            e.printStackTrace();
        }//catch
    }//while
}//run

////accepting new client

while (running) {
        try {
            clientConnecting = serverSocket.accept();
            new TCPServerHandle(clientConnecting).start();
                            Thread.sleep(10);
        }//try
        catch (Exception e) {
            e.printStackTrace();
        }//catch
   }//while
Était-ce utile?

La solution

You could deffinitely create a second ServerSocket for the "party" to communicate with the host. Incoming packets are demultiplexed to the correct process, using port numbers. You can set multiple TCPServerSockets to listen and accept incoming connection requests on different ports.

ServerSocket welcomeSocket = new ServerSocket(portNumber);
Socket clientSocket = welcomeSocket.accept();

And yes, it is in many cases more efficient to use a combination of TCP and UDP, because as you mention some data is more critical than other. UDP only provides a best effort service, where packets can get lost. If you want to setup a UDP socket:

DatagramSocket UDPSocket = new DatagramSocket();

Autres conseils

Using blocking I/O with Object I/O streams aren't optimal conditions for an RTS because you don't want other clients to wait during the login process of another client. You might be thinking that you could just multi-thread everything to avoid the wait but it wouldn't make much of a difference because there are still blocking read/write operations. Also, with Object I/O streams, all objects sent have to be serialized first (known as serialization), which could be a pretty lengthy process depending on your user-base. If there are a lot of players, literally every millisecond counts. You should use non-blocking I/O (such as NIO) along with ByteBuffers. I would suggest looking at an NIO tutorial instead, this is a very detailed tutorial on how to make a simple server-client application.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top