简体   繁体   中英

Socket connections managing in Java

I am making a simple multiplayer game in java. The point is, that I need server app to be able receive data from multiple client apps. Example: I have 2 client apps connected. Server is waiting for the data from any client. When game character is moved using the first client app, the data with the new coordinates must be sent to the server app, and then the new position of a character must be broadcasted to all of the clients. I've read that this can be accomplished using making a new thread for each client connection, but is there a better way to do that? Won't server crash if we start for example 100 threads?

Thanks for all replies, cyanide

You should use a socket pool to manage you sockets. A quick google brings me to this example but you can find a lot more. If you need to handle more than 100 threads this is probably not a simple multiplayer game anymore that you should use as a first project in this.

You never need to create a new thread to process a new client connection. You can create if you wish, but that not needed at all.

Please find below the approach that you can follow.

Have a server with: 1) One thread which accepts new connection, creates session and add new player in existing game. So you can say it as a management thread.

2) One thread which will just use epoll/select on sockets fds. Any read write on any socket will be notified on this thread.

3) Have N (depending on many factors especially cores of servers), lets say 5 worker threads(thread pool), whose job will be to broadcast the data on all the sockets which are part of the game session, except the thread that originated the request.

So when you will receive any data on any socket, you get notification on thread 2(epoll thread), then you will ask one of the worker thread to broadcast the data to all the related sockets

Important point to look for is how much times you have to wait for a worker thread so that you can push your work on the worker. This is something which needs tweaking depending on use cases.

Just to add something more to it:

So now how you will scale this solution. This will be dependent upon the number of game session and you can have load balancer which will always start a new games on the machine which has lowest number of resource used.

如果您在Linux上执行此操作,则有限制配置以限制套接字连接/ proc / sys / net的数量,该数目控制如何打开tcp / ip套接字,并且只要套接字连接数低于该值,就应该没事的。

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