为什么要使用非阻塞或阻塞套接字

为什么要使用非阻塞或阻塞套接字

本文介绍了为什么要使用非阻塞或阻塞套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我必须问,哪个州是最好的?例如实时MMORPG服务器。如果我为每个客户端创建线程而不是使用非阻塞套接字,该怎么办?或者如果我使用一个包含所有非阻塞套接字的线程怎么办?你能解释我的优点吗?

解决方案

你的问题值得讨论一个更长的时间, p>


  • 使用阻止套接字意味着任何一个线程中只有一个套接字在任何时候都是活动的(因为在等待活动时阻塞) >
  • 使用阻塞套接字通常比非阻塞套接字容易(异步编程往往更复杂)

  • 线程有开销 - 你将无法创建非常多的(通常任何超过10-20线程被认为坏习惯)

  • 与非阻塞套接字,你可以处理一个



使用非阻塞方式(在Windows上)您有几个选项:




  • 查询

  • li>
  • 重叠I / O



重叠的I / O会为您提供最佳性能/ process),代价是最复杂的模型,以便正确理解和实现。



基本上,它归结为性能与编程复杂性。





这里有一个更好的解释为什么使用线程/套接字模型是一个坏主意:



在窗口中,创建大量线程是非常低效的,因为调度程序无法正确确定哪些线程应该接收处理器时间和应该't。这与每个线程的内存开销相结合意味着在操作系统级别你将耗尽内存(因为堆栈空间)和处理器周期(因为管理线程的开销),否则你将耗尽容量来处理套接字连接。所以,是的,你可以生成一个进程,可以处理可能达到100或甚至更多的客户端这种方式,但它永远不会有效或能够处理数千连接。


At first, I must ask that which is the best in which states ? For example a real-time MMORPG server. What if i create a thread per client instead of using non-blocking sockets ? Or What if i use one thread that contains all non-blocking sockets ? Can you explain me the advantages ?

解决方案

Your question deserves a much longer discussion but here's a short stab at an answer:

  • using blocking sockets means that only one socket may be active at any time in any one thread (because it blocks while waiting for activity)
  • using blocking sockets is generally easier than non-blocking sockets (asynchronous programming tends to be more complicated)
  • you could create 1 thread per socket as you stated but threads have overhead - you will not be able to create very many of them (usually anything more than 10-20 threads is considered bad practice)
  • with non-blocking sockets you could handle a much larger volume of clients: hundreds or even thousands in a single process - but the code become a little bit more complicated

With non-blocking sockets (on Windows) you have a couple of options:

  • polling
  • events based
  • overlapped I/O

Overlapped I/O will give you the best performance (thousands of sockets / process) at the expense of being the most complicated model to understand and implement correctly.

Basically it comes down to performance vs. programming complexity.

NOTE

Here's a better explanation of why using a thread/socket model is a bad idea:

In windows, creating a large number of threads is highly inefficient because the scheduler is unable to properly determine which threads should be receiving processor time and which shouldn't. That coupled with the memory overhead of each thread means that you will run out of memory (because of stack space) and processor cycles (because of overhead in managing threads) at the OS level long before you will run out of capacity to handle socket connections. So, yeah, you may be able to generate a process that could handle maybe up to 100 or maybe even a bit more clients this way but it will never be efficient or be able to handle thousands of connections.

这篇关于为什么要使用非阻塞或阻塞套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 21:50