使用.NET什么是不'每个客户端的线程'服务器的基本算法?
编辑我正在寻找一个基本的3,4行5行算法/伪代码/模式,描述服务器正在使用的一般过程。
与此相反:
open a server socket // this uses the port the clients know about
while(running)
client_socket = server_socket.listen
fork(new handler_object(client_socket))
答案 0 :(得分:2)
事件循环。等待套接字变为可写,写入它们,等待连接,接受它们等等。在大多数情况下,这种方法比线程更具可伸缩性,因为通常不需要多个闭包来跟踪客户端的状态。 (你当然不需要整个过程,因为prefork服务器似乎在思考。)
答案 1 :(得分:2)
答案 2 :(得分:2)
一个循环,它调用Select
,确定哪些套接字(客户端)已就绪,然后读取和/或写入这些套接字,在没有套接字就绪时进行必要的处理。
伪代码:
loop {
to_read.add(client1);
to_read.add(client2);
select(to_read, timeout = 0.5);
for client in to_read { // to_read is modified by select
data = client.read
handle(data)
}
if to_read is empty {
do_bookeeping()
}
}
答案 3 :(得分:2)
Ian Griffiths有excellent (.NET) introduction来处理多个客户端而无需为每个客户端使用一个线程。
答案 4 :(得分:1)
线程池将允许服务器拥有比客户端更少的线程。
答案 5 :(得分:1)
使用事件队列和线程池,例如:
when [something happens] then
[create an event for something]
[put it in the queue]
也:
while [something in queue]
if [thread is available] then
remove [thing] from queue
run [thing-response] on [available thread]
else [wait a little while]
这种架构非常具有可扩展性
答案 6 :(得分:0)
您可以为每个请求执行一个线程,受线程池限制。但是您可能对处理此问题的异步方法感兴趣。这个页面很好地说明了异步方法的工作原理:
答案 7 :(得分:0)
Socket.BeginAccept - >在回调中AuthenticatedStream。BeginAuthenticateAsServer - >在回调流中。BeginRead - >在回调后发布新的BeginRead,处理请求然后流。BeginWrite响应。
如果确实不需要,您可以取出经过身份验证的流部分(SSL或Kerberos / NTLM),然后它变为: Socket.BeginAccept - >在回调套接字中。BeginReceive - >在回调中发布新的BeginReceive,然后处理请求socket BeginWrite响应。