2011-08-21 43 views
3

长时间休息后,我试图刷新我对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

错误发生在调试服务器代码 – RStyle

+0

哪一行抛出异常? – svick

回答

5

的错误是由于在您的接受功能下面一行:

AsyncSocket.EndAccept(_IAsyncResult); 

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

Socket dataSocket = AsyncSocket.EndAccept(_IAsyncResult); 

您还需要这个新的socket传递给BeginReceive功能参数为:

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

这非常有帮助,而且很容易犯这样的错误。 – Zapnologica