问题
I'm writing a game server in Java. As common in game servers, I must take data received by one client and distribute it over the client's room (other clients). Currently, each client spawns its own thread and works on top of that. I'm having trouble, however, to define the inter-player relations. How do I control something like chat, where a message must be echo'ed to all the other players in the same room? I'm thinking in something like a message queue, where all threads would often look for messages and send them to its own client.
I'm also open to suggestions that would ditch multithreading at once, but I'm not familiar with NIO and the server is already written using plain Socket
s and Thread
s.
Summary: How do I make my clients (in threads) talk to each other? Or is there a better non-threaded alternative to this?
回答1:
One approach I have used is to design a Server class and a class which extends Thread.
The Server class will spawn all of your threads, and keep a list of all currently running threads it has created.
In your Thread class, use the Socket object to create your input / output streams. When one of these threads has something to say, it will talk to the server through the stream, and then it is up to the server to deliver that message to all of its currently running threads.
This really simple java tutorial actually helped me out a lot.
https://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
回答2:
My proposed solution too is similar to Jakeway. I have exactly implemented the same feature in this way.
Server will create one thread and create Server Socket in that thread and waits for connection
Client will connect to Server. Server will create ClinetSocket and pass this socket to thread. This thread is responsible for client/server communication from server
Form the client side, on creation of Socket, one thread will start and that thread is responsible for client/server communication from client
Have a look some of ready-made code from below links.
chat example 1
chat example 2
Regarding Pros & Cons of socket usage, visit below link : rmi vs servlets vs sockets
Regarding clients communication between them ? Not feasible. Client will send message to server & server should send message to other client. If you look at Yahoo kind of chat
1) You will send message to server in a chat room
2) Server have list of client subscribed clients to the chat room
3) Server will send message to all the clients subscribed to room
回答3:
Hey i made a library just for that! https://www.dropbox.com/s/xcy1uyyyc610lb5/JSock.rar?dl=0 Just download it and import it into your project. Read ReadMe.txt it will explain most of the stuff. If you need me to explain more just ask!
来源:https://stackoverflow.com/questions/27424845/java-multithreaded-server