socket接收数据一定要写在一个死循环里吗
发布网友
发布时间:2022-05-02 23:27
我来回答
共1个回答
热心网友
时间:2022-06-28 08:21
将接收数据的过程交给其他线程处理,或者使用如 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();
}