简体   繁体   English

C ++ winsock服务器中的非阻塞模式与异步套接字不同

[英]Different between none-blocking mode with async socket in C++ winsock server

In C++, I've read some tutorials to create a server which can accept connections from multiple clients. 在C ++中,我已经阅读了一些教程来创建一个可以接受来自多个客户端的连接的服务器。 They suggest using async socket, but i don't really know why we should choose async over none-blocking mode. 他们建议使用异步套接字,但我真的不知道为什么我们应该在非阻塞模式下选择异步。 And what's about the ideas that use multi-threading? 什么是使用多线程的想法? is it better than using async socket? 它比使用异步套接字更好吗? Thanks!! 谢谢!!

Since you're requesting a solution in C++, boost asio is imo the best async io library there is. 由于您正在使用C ++请求解决方案,因此boost asio是最好的异步io库。

I assume you're talking about the "one thread per client" solution when refering to "multi-threading", which is generally a very bad idea for servers who expect many clients in a short time frame or connected at the same time. 我假设您在谈到“多线程”时所说的“每个客户端的一个线程”解决方案,对于期望在短时间内或同时连接多个客户端的服务器而言,这通常是一个非常糟糕的主意。 Threads are way to resource consuming for this use, plus you have to take care of mutual exclusion, which in combination with blocking calls can drive you into deadlocks very fast. 线程是用于此用途的资源消耗的方式,此外,您必须处理互斥,这与阻塞调用相结合可以非常快速地导致死锁。 And thats the least worst of what you can run into. 这是你遇到的最糟糕的事情。

Additionally on that, it's very easy for an attacker to exploit your server to stuck. 此外,攻击者很容易利用您的服务器卡住。 You will spend much time on trying to design your code so that this will be avoided, which leads you into having an unreadable, hard to update and error phrone code. 您将花费大量时间尝试设计代码,以避免这种情况,从而导致您出现难以理解,难以更新和错误的错误代码。

In boost.asio the specified thread(s) ( those who call io_service::run ) will only do work when there is actually work to do, directly leading you into the object assigned to the task. 在boost.asio中,指定的线程(调用io_service :: run的那些线程)只有在实际工作时才会工作,直接引导您进入分配给该任务的对象。 So technically async is also blocking, with the difference that only the scheduler waits for work to do, while those functions you add work with ( connect, send, receive, ... ) will return immediately. 因此技术上异步也是阻塞的,区别在于只有调度程序等待工作,而你添加的那些函数(connect,send,receive,...)将立即返回。

I'll assume you're talking TCP and not UDP. 我假设你说的是TCP而不是UDP。 I definitely recommend skipping async sockets, those are favored by Microsoft and supporters but are not portable. 我绝对建议跳过异步套接字,这些都受到微软和支持者的青睐,但不可移植。 Instead use the vanilla stuff: here's an example with server and client . 而是使用vanilla的东西: 这是 服务器客户端 的一个例子

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

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