【发布时间】:2019-09-10 13:59:11
【问题描述】:
我正在关注有关创建异步套接字服务器 (here) 的 MSDN 教程。我需要服务器能够持续收听来自客户端的消息,在查看了here 和here 的答案后,我得到了这样的结果:
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// Message received, do something
// ...
}
else
{
// Not all data received. Get more
// ...
}
}
// Continue waiting
handler.BeginReceive(state.buffer, 0, SocketState.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
我的问题是,这种方法是否会无限增长堆栈,因为它递归调用ReadCallback()?
【问题讨论】:
-
你没有做递归。您在返回之前使用 AsyncCallback 注册一个新事件。堆栈大小不会增长。
-
@jdweng 好的,那么这些解决方案很有意义。谢谢!
标签: c# sockets asynchronous