简体   繁体   English

非阻塞select()?

[英]Non-blocking select()?

I'm trying to implement simple networking game (client - server) which uses UDP to transfer game events over network, and I have this working well, but now I would like to add to game chat over tcp in same console application. 我正在尝试实现简单的网络游戏(客户端-服务器),该游戏使用UDP通过网络传输游戏事件,并且我的工作情况很好,但是现在我想在同一控制台应用程序中通过tcp进行游戏聊天。 I've tried to implement multi client chat using select() and non-blocking master socket. 我尝试使用select()和非阻塞主套接字实现多客户端聊天。 Chat is working as standalone application but I have problems putting it together. 聊天正在作为独立应用程序运行,但是将其组合在一起时遇到了问题。

Basically my server loop looks like this: 基本上,我的服务器循环如下所示:

while(true)
{
    sendUDPdata()
    ...

    while(true)
    {
        receiveUDPdata()
    }
}

Problem is that when I want to add chat to server's main loop (handling UDP) like this: 问题是,当我想像这样将聊天添加到服务器的主循环(处理UDP)时:

while(true)
{
    HandleTCPConnections();

    sendUDPdata();
    ...

    while(true)
    {
        receiveUDPdata();
    }
}

calling select() in HandleTCPConnections() blocks whole server. HandleTCPConnections()调用select()阻塞整个服务器。 Is there any way how to handle this? 有什么办法可以解决这个问题?

There are two good ways to do this: 有两种很好的方法可以做到这一点:

  1. Use threads. 使用线程。 Have a thread to handle your TCP sockets and a thread to handle your UDP sockets. 有一个线程来处理您的TCP套接字,并有一个线程来处理您的UDP套接字。

  2. Use a reactor. 使用电抗器。 Both the UDP code and the TCP code register their sockets with the reactor. UDP代码和TCP代码都将其套接字注册到反应堆。 The reactor blocks on all the sockets (typically using poll ) and calls into the appropriate code when activity occurs on that socket. 反应器在所有套接字上阻塞(通常使用poll ),并在该套接字上发生活动时调用相应的代码。

There are lots of libraries out there for both of these options (such as libevent and boost.asio ) that you can use if you don't want to reinvent the wheel. 如果您不想重新发明轮子,可以使用很多库来使用这两个选项(例如libeventboost.asio )。

select is a blocking call if there's no data available from the sockets, in your case. 如果您的套接字没有可用数据,则select 阻塞调用。

Your chat can either run along with the server or in parallel with it: you've already got the first case; 您的聊天可以与服务器一起运行,也可以与服务器并行运行。 for the second, you'd better go for a separate thread that handles the chat. 第二,您最好选择一个单独的线程来处理聊天。 C++ has <thread> , which you may want to look into. C ++具有<thread> ,您可能需要研究一下。

A separate thread is easier to implement in this case because you've a separate connection, and separate sockets therefore, that would otherwise need to be looked after for concurrent access. 在这种情况下,使用单独的线程更容易实现,因为您拥有单独的连接,因此也有了单独的套接字,否则,在进行并发访问时需要注意这一点。

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

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