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

发布于 2024-08-23 05:59:21 字数 246 浏览 8 评论 0原文

我正在用 C++ 和 OpenGL 开发一个游戏。我已经制作了一个线程服务器,它现在接受客户端(游戏)并接收来自它们的消息。目前游戏仅发送消息。我希望游戏和服务器都能够发送和接收,但我不确定最好的方法。我正在考虑使用一个线程用于发送,一个线程用于接收,两者都在同一个套接字上。现在游戏在单线程中运行,服务器为每个客户端创建一个单独的线程。

寻找有关如何针对游戏和服务器进行操作的建议(除非您的建议对两者相同)。如有任何疑问,请随时提问:)

谢谢!

I have a game I am working on in C++ and 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦一生花开无言 2024-08-30 05:59:21

您需要做的是为每个客户端设置一个消息传出队列。假设您有 2 个客户端连接到服务器,一个由线程 A 提供服务,另一个由线程 B 提供服务。线程 A 应该在其套接字和信号量/互斥体/条件变量上执行 WaitOnMultipleObjects()为其队列。这样,如果它的队列中有东西,它可以醒来并将其发送出去。如果它从客户端收到不需要给客户端 B 的消息,它将处理该消息并将其放入线程 B 的传出队列中。

这是一个非常简单的同步方案。如果你的游戏非常复杂或庞大,你将不得不做一些比这更聪明的事情。

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. 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.

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.

墨洒年华 2024-08-30 05:59:21

不要在游戏服务器中使用线程。许多专业的 AAA 游戏服务器都是单线程的——事实上,我见过的每一个都是单线程的。

Don't use threads in a game server. Many professional, AAA game servers are single-threaded - every one I've ever seen, in fact.

征棹 2024-08-30 05:59:21

考虑使用 Boost.ASIO,它通过 C++ API 很好地实现了这一点(除了异步 I/O 之外,还允许许多不同的方法)。有很多教程。但是,为了获得绝对最高的性能,您可能不应该使用线程。

Consider using Boost.ASIO that implements this well with a C++ API (allowing many different approaches besides just asynchronous I/O). There are plenty of tutorials. However, for the absolute highest performance, you should probably not use threads.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文