c# socket 异步通信 的一个问题
下面两个函数是clientsocket类中的两个方法,我想定义一个client类,然后通过receive方法返回读取的内容,但是程序运行到下面老是卡住,运行一分钟左右然后...
下面两个函数是clientsocket类中的两个方法, 我想定义一个client类, 然后通过 receive 方法 返回读取的内容, 但是程序运行到下面老是卡住, 运行一分钟左右 然后返回空 , 经过我单步调试,发现在第一次读取数据调用receivecallback之后,读取数据不为0,循环调用receivecallback,但是然后系统就卡住了,大约四五十秒(估计连接已经断开),然后才再调用receivecallback, 然后才bytesread=0, receiveDone.Set()执行后, receivecallback并没有被退出,而是继续执行下去了。 有大神知道怎么回事吗?
public string Receive()
{
try
{
response = "";
StateObject state = new StateObject();
state.workSocket = client;
receiveDone.Reset();
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
receiveDone.WaitOne();
return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void ReceiveCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// 有数据,存储.
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
response = state.sb.ToString();
// 所有数据读取完毕的指示信号.
receiveDone.Set();
}
} 展开
public string Receive()
{
try
{
response = "";
StateObject state = new StateObject();
state.workSocket = client;
receiveDone.Reset();
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
receiveDone.WaitOne();
return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void ReceiveCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// 有数据,存储.
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
response = state.sb.ToString();
// 所有数据读取完毕的指示信号.
receiveDone.Set();
}
} 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询