System.Net.SocketException因为没有连接Socket

时间:2014-07-31 08:33:33

标签: c# sockets network-programming

我是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

提前致谢

1 个答案:

答案 0 :(得分:1)

您的问题是您正在尝试从侦听套接字读取数据,就像正在接收数据的套接字一样。使用套接字Listen时,它仅用于调用Accept来接受连接,然后读取和写入随后连接的套接字。因此,例外情况是告诉您正在尝试从没有连接的套接字读取,这是正确的,因为尚未接受任何套接字。