简体   繁体   English

在C ++ / WinSock中制作(线程化)游戏服务器

[英]Making (threaded) game server in C++/WinSock

I have a game I am working on in C++ and OpenGL. 我正在使用C ++和OpenGL进行游戏。 I have made a threaded server that right now accepts clients (the game) and receives messages from them. 我已经制作了一个线程服务器,它现在接受客户端(游戏)并从它们接收消息。 Right now the game only sends messages. 现在游戏只发送消息。 I want both the game and server to be able to send and receive, but I'm not sure the best way to go about it. 我希望游戏和服务器能够发送和接收,但我不确定最好的方法。 I was considering using a thread for sending and one for receiving, both on the same socket. 我正在考虑使用一个线程进行发送,一个用于接收,两者都在同一个套接字上。 Right now the game runs in a single thread, and the server makes a separate thread for each client. 现在游戏在一个线程中运行,服务器为每个客户端创建一个单独的线程。

Looking for suggestions on how to go about it for the game as well as the server (unless your suggestion is the same for both). 寻找有关如何为游戏和服务器进行操作的建议(除非您的建议对于两者都相同)。 Any questions, feel free to ask :) 有任何问题请随时询问我(们 :)

Thanks! 谢谢!

What you need to do is set up an outgoing queue of messages for each client. 您需要做的是为每个客户端设置一个传出的消息队列。 Say you have 2 clients connected to the server, one being serviced by thread A and the other by thread B. Thread A should do a WaitOnMultipleObjects() on its socket and on a semaphore/mutex/condition variable for its queue. 假设您有2个客户端连接到服务器,一个由线程A提供服务,另一个由线程B提供服务。线程A应在其套接字上执行WaitOnMultipleObjects()并在其队列的信号量/互斥/条件变量上执行。 That way, if it gets something in its queue, it can wake up and send it out. 这样,如果它在队列中得到某些东西,它就可以唤醒并发送出去。 If it gets a message from the client that it needs no give to client B, it will process that message and put it in thread B's outgoing queue. 如果它从客户端收到一条消息,它不需要提供给客户端B,它将处理该消息并将其放入线程B的传出队列中。

This is a very simple synchronization scheme. 这是一种非常简单的同步方案。 If your game is very complex or massive, you will have to do something much more clever than this. 如果你的游戏非常复杂或庞大,你将不得不做一些比这更聪明的事情。

Don't use threads in a game server. 不要在游戏服务器中使用线程。 Many professional, AAA game servers are single-threaded - every one I've ever seen, in fact. 事实上,许多专业的AAA游戏服务器都是单线程的 - 每一个我都见过的。

Consider using Boost.ASIO that implements this well with a C++ API (allowing many different approaches besides just asynchronous I/O). 考虑使用Boost.ASIO,它可以通过C ++ API实现这一点(除了异步I / O之外,还允许许多不同的方法)。 There are plenty of tutorials . 有很多教程 However, for the absolute highest performance, you should probably not use threads. 但是,对于绝对最高性能,您可能不应该使用线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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