可以处理多个客户端的单一TCP/IP服务器(在C ++中)? [英] Single TCP/IP server that handles multiple clients (in C++)?

查看:463
本文介绍了可以处理多个客户端的单一TCP/IP服务器(在C ++中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C ++(使用bind()accept()等)编写一个TCP/IP服务器,该服务器可以处理多个同时连接到它的客户端. 我已经阅读了一些与此相关的主题,每个人都在提出以下建议(出现肮脏的伪代码):

I want to write a TCP/IP server in C++ (using bind(), accept() etc.) that can deal with multiple clients connecting to it at the same time. I have read a few topics about this, and everyone is suggesting the following (dirty pseudocode coming up):

set up server, bind it

while (1) {
    accept connection
    launch new thread to handle it
}

这在具有多个线程的计算机上完全可以正常工作.但是我的目标系统是没有任何硬件线程的单核计算机.为了进行一些测试,我尝试通过系统上的std::thread启动多个线程,但是它们是一个接一个地执行的.没有平行善良:(

Which would work totally fine on a machine that has multiple threads. But my target system is a single core machine without any hardware threads. For a little test, I tried launching multiple threads via std::thread on the system but they were executed one after the other. No parallel goodness :(

这使得无法实现上述算法.我的意思是,我确定可以做到,我只是不知道该怎么做,因此,我将非常感谢您的帮助.

That makes it impossible to implement the algorithm above. I mean, I'm sure it can be done, I just don't know how, so I would really appreciate any help.

推荐答案

您不需要线程,需要异步或事件驱动"编程.如果要跨平台,可以使用select()来完成;如果要使用Linux,并且要一次支持数千个客户端,则可以使用epoll()来完成.

You don't need threads, you need asynchronous or "event-driven" programming. This can be done with select() if you want cross-platform, or epoll() if you're on Linux and want to support thousands of clients at once.

但是您不需要从头开始实现所有操作-您可以使用提升ASIO (其中某些可能会成为C ++ 17的一部分)或类似 libevent libev

But you don't need to implement this all from scratch--you can use Boost ASIO (some of which may become part of C++17) or a C library like libevent or libev or libuv. Those will handle a bunch of subtle details for you, and help you get more quickly to the real business of your application.

这篇关于可以处理多个客户端的单一TCP/IP服务器(在C ++中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆