C# System.Net.SocketException,因为未连接套接字
我是套接字编程新手。我试着写一篇C#chat。每次调用此函数时:C# System.Net.SocketException,因为未连接套接字,c#,sockets,network-programming,C#,Sockets,Network Programming,我是套接字编程新手。我试着写一篇C#chat。每次调用此函数时: void starteServer() { try { IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress localIpAddress = ipHostInfo.AddressList[0]; IPEndPoint localendpoint
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,原因是套接字未连接。我想我打断了接收(服务器)线路。这是接收方法:
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();
}
}
希望有人能解释我的这种行为,并帮助我解决它
如果需要代码的其余部分,请访问:
提前感谢您的问题是您试图从侦听套接字读取数据,就像是套接字接收数据一样。当您使用套接字时,它仅用于调用以接受连接,然后读取和写入后续连接的套接字。因此,例外情况是告诉您,您正在尝试从未连接到任何位置的套接字读取数据,这是正确的,因为尚未接受任何套接字