经过长时间休息,我试图刷新我对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);
}
客户代码:
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);
}
答案 0 :(得分:5)
错误是由于Accept函数中的以下行:
AsyncSocket.EndAccept(_IAsyncResult);
服务器侦听特定套接字,并使用它来接受来自客户端的连接。您不能使用相同的套接字来接受连接并从客户端接收数据。如果你看看Socket.EndAccept的帮助,它会说它创建了一个新的Socket来处理远程主机通信。在您的代码中,您使用_Socket来侦听客户端连接和接收数据。您可以将此行修改为:
Socket dataSocket = AsyncSocket.EndAccept(_IAsyncResult);
您还需要将此新套接字传递给BeginReceive函数参数:
AsyncSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Receive), dataSocket);