最有效的方式来处理客户端连接(socket编程) [英] Most efficient way to handle a client connection (socket programming)
问题描述
有关的每一个教程和示例我已经看到了互联网的Linux / Unix套接字教程,服务器端code总是涉及到一个无限循环来检查每一次客户端连接。
例如:
For every single tutorials and examples I have seen on the internet for Linux/Unix socket tutorials, the server side code always involves an infinite loop that checks for client connection every single time. Example:
http://www.thegeekstuff.com/2011/12/c -socket编程/
http://tldp.org/LDP/LG/issue74/tougher。 HTML 3.2#
是否有来构造服务器侧code,使得它不涉及一个无限循环,或更有效的方式code的方式,这将占用较少的系统资源的无限循环
Is there a more efficient way to structure the server side code so that it does not involve an infinite loop, or code the infinite loop in a way that it will take up less system resource?
推荐答案
在这些例子中无限循环已经是有效的。调用接受()
是一个阻塞调用:该函数不返回,直到有连接到服务器的客户端。 code为执行其称为接受线程()
功能停止,并且不采取任何的处理能力。
the infinite loop in those examples is already efficient. the call to accept()
is a blocking call: the function does not return until there is a client connecting to the server. code execution for the thread which called the accept()
function is halted, and does not take any processing power.
认为的接受()
),则不能调用加入(
或像一个互斥/锁等待/信号灯。
think of accept()
as a call to join()
or like a wait on a mutex/lock/semaphore.
当然,还有许多其他的方式来处理传入的连接,但这些其他的方式处理的阻塞性接受()
。这个功能是困难的取消,所以存在非阻塞替代,这将允许服务器以执行其它动作同时等待传入连接。这样的一个方法是使用选择()
。其他替代品,因为它们涉及低层操作系统调用的信号通过回调函数的事件由操作系统处理的任何其它异步机制的连接,或更小的便携式...
of course, there are many other ways to handle incoming connection, but those other ways deal with the blocking nature of accept()
. this function is difficult to cancel, so there exists non-blocking alternatives which will allow the server to perform other actions while waiting for an incoming connection. one such alternative is using select()
. other alternatives are less portable as they involve low-level operating system calls to signal the connection through a callback function, an event or any other asynchronous mechanism handled by the operating system...
这篇关于最有效的方式来处理客户端连接(socket编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!