经过长时间的休息,我试图刷新我对 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);
}
最佳答案
错误是由于您的 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);
关于c# - 发送或接收数据的请求被拒绝,因为套接字未连接。 .,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7136316/