由于未连接套接字,因此不允许发送或接收数据的请求..

RSt*_*yle 3 c# sockets exception

经过长时间的休息,我试图刷新我对System.Net.Sockets的记忆,但我遇到了连接甚至2台机器的问题.

例外:不允许发送或接收数据的请求,因为套接字未连接(当使用sendto调用在数据报套接字上发送时)没有提供地址

服务器代码:

private void startButton_Click(object sender, EventArgs e)
        {
            LocalEndpoint = new IPEndPoint(IPAddress.Parse("192.168.1.103"), 4444);
            _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _Socket.Bind(LocalEndpoint);
            _Socket.Listen(10);
            _Socket.BeginAccept(new AsyncCallback(Accept), _Socket);
        }

private void Accept(IAsyncResult _IAsyncResult)
        {
            Socket AsyncSocket = (Socket)_IAsyncResult.AsyncState;
            AsyncSocket.EndAccept(_IAsyncResult);

            buffer = new byte[1024];

            AsyncSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Receive), AsyncSocket);
        }

        private void Receive(IAsyncResult _IAsyncResult)
        {
            Socket AsyncSocket = (Socket)_IAsyncResult.AsyncState;
            AsyncSocket.EndReceive(_IAsyncResult);

            strReceive = Encoding.ASCII.GetString(buffer);

            Update_Textbox(strReceive);

            buffer = new byte[1024];

            AsyncSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Receive), AsyncSocket);
        }
Run Code Online (Sandbox Code Playgroud)

客户代码:

 private void connectButton_Click(object sender, EventArgs e)
        {
            RemoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.103"), 4444);
            _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _Socket.BeginConnect(RemoteEndPoint, new AsyncCallback(Connect), _Socket);
        }

 private void Connect(IAsyncResult _IAsyncResult)
        {
            Socket RemoteSocket = (Socket)_IAsyncResult.AsyncState;
            RemoteSocket.EndConnect(_IAsyncResult);
        }
Run Code Online (Sandbox Code Playgroud)

小智 5

该错误是由于Accept函数中的以下行:

AsyncSocket.EndAccept(_IAsyncResult);
Run Code Online (Sandbox Code Playgroud)

服务器侦听特定套接字,并使用它来接受来自客户端的连接.您不能使用相同的套接字来接受连接并从客户端接收数据.如果你看一下Socket.EndAccept的帮助,它会说它创建了一个新的Socket来处理远程主机通信.在您的代码中,您使用_Socket来侦听客户端连接和接收数据.您可以将此行修改为:

Socket dataSocket = AsyncSocket.EndAccept(_IAsyncResult);
Run Code Online (Sandbox Code Playgroud)

您还需要将此新套接字传递给BeginReceive函数参数:

AsyncSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Receive), dataSocket);
Run Code Online (Sandbox Code Playgroud)