socket接收数据一定要写在一个死循环里吗
展开全部
将接收数据的过程交给其他线程处理,或者使用如 clawclaw(唏嘘的胡渣) 提供的异步接收方式。不使用while死循环!
参考:
private System.Threading.ManualResetEvent receiveEvent = new System.Threading.ManualResetEvent(false);
private void ReceiveData()
{
while (true)
{
receiveEvent.Reset();
if (m_Socket != null && m_Socket.Connected)
{
StateObject stateObject = new StateObject();
stateObject.workSocket = m_Socket;
NetworkStream stream = new NetworkStream(m_Socket);
try
{
stream.BeginRead(stateObject.buffer, 0, MaxBuffer, new AsyncCallback(ReceiveData), stateObject);
}
catch
{
}
}
receiveEvent.WaitOne();
}
}
private void ReceiveData(IAsyncResult ar)
{
receiveEvent.Set();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询