我是Socket编程的新手。我尝试写一个C#聊天。每当我调用此函数时:
void starteServer()
{
try {
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress localIpAddress = ipHostInfo.AddressList[0];
IPEndPoint localendpoint = new IPEndPoint(localIpAddress, serverPort);
server.Bind(localendpoint);
server.Listen(10);
Recive(server);
lb_chat.Items.Add(response);
receiveDone.WaitOne();
}
catch (Exception e)
{
errorHandler(e);
}
}
我得到一个System.Net.SocketException,其原因是未连接的Socket。我想我在Recive(服务器)线上打破了。这是Recive方法:
private static void Recive(Socket client)
{
try
{
StateObjeckt state = new StateObjeckt();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObjeckt.bufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
errorHandler(e);
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
StateObjeckt state = (StateObjeckt)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, StateObjeckt.bufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
希望有人可以解释我这种行为,并帮助我解决它。
如果您需要其余代码,请访问: https://gist.github.com/chrishennig/ea4b5a974fc6f9aa2bb6
提前致谢