在套接字编程中,将Listen()侦听数量置为1,仍允许一个以上的客户端连接
在套接字编程中,将Listen()侦听数量置为1,仍允许一个以上的客户端连接,为什么呢?
private void button_StartServer_Click(object sender, EventArgs e)
{
String strHostName = "";
try
{
strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry( strHostName );
}
catch( Exception ex )
{
Console.WriteLine ("Error trying to get local address {0} ", ex.Message );
}
//创建一个套接字
m_sServer = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
//绑定套接字到端口
m_sServer.Bind(new IPEndPoint(IPAddress.Parse(tbServIP.Text), int.Parse(textBox_port.Text)));
//侦听是否有连接传入,指定挂起的连接最大值为1
m_sServer.Listen( 1 );
//开始一个异步操作来接受一个传入的连接尝试
//采用 IAsyncResult 参数,该参数随后可用来获取异步操作的结果
m_sServer.BeginAccept( new AsyncCallback( OnConnectRequest ), m_sServer);
}
[解决办法]
这个是表明Socket进行监听处理的队列容量。例如你去银行办事,窗口只有5个但人很多就得排队,银行会自己设定一个合适的排队长度(就相当于你设置的backlog数目),例如只能有20个人在等待,人再多5个窗口就忙不过来了。
如果你是第21个到达的,那你就会被告知一个消息,说你暂时不能进入银行排队等候。这个在MSDN有描述:The listen function is typically used by servers that can have more than one connection request at a time. If a connection request arrives and the queue is full, the client will receive an error with an indication of WSAECONNREFUSED.
详细内容的地址:http://technet.microsoft.com/zh-cn/library/aa924101。
所以你设置数目1适合你连接的客户端数目是没有关系的。1相当于是排队的长度,但银行是可以为多人服务的。也就是说监听socket可以接入多个客户端连接。
[解决办法]
你只是看着超过而已。。但计算机处理的速度很快,你添加的时候计算机都已经处理完成了,可以一直保持的队列空余。。。所以你简单测实测不出来的