BeginReceiveFrom()为null?

时间:2017-09-21 00:53:31

标签: c# sockets unity3d

我一直想在windows .net套接字中设置UDP客户端/服务器。 在下面的客户端脚本中,当客户端连接"时,我能够向服务器发送消息,但是当我尝试调用BeginToReceeve()函数时,我得到一个空引用。

我很困惑为什么我可以发送消息(当然使用服务器端点),但由于空错误而无法接收。我是套接字的新手,我想知道为什么这不起作用?

服务器在windows c#应用程序中运行,客户端在Unity3D的c#脚本中运行。

private EndPoint epServer;
private Socket clientSocket;
private byte[] myBuffer = new byte[1024];

private void ConnectToServer ( ) {  
    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    IPEndPoint server = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 61456);//Connect to the Local server 
    epServer = (EndPoint)server; //Access the server

    WritePacketAndSend("Hello Server");//This creates the packet and uses the BeginToSend() function to send the string to the server

    try{
         clientSocket.BeginReceiveFrom(myBuffer, 0, myBuffer.Length, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), epServer);//<<< Null reference here not sure why...
    } catch(Exception ex) {
         print(ex.Message); //Keep getting: Object reference not set to an instance of an object
    }
}

private void ReceiveData(IAsyncResult ar){

   print("Entered ReceiveData");//The code never enters here

  try{                              
       IPEndPoint server = new IPEndPoint(IPAddress.Parse("127.0.0.1", 61456);
       epServer = (EndPoint)server;
       clientSocket.EndReceiveFrom(ar, ref epServer);

       clientSocket.EndReceive(ar);     

       print(Encoding.UTF8.GetBytes(myBuffer));

       clientSocket.BeginReceiveFrom(myBuffer, 0, myBuffer.Length, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), epServer, 

      } catch (Exception ex){
          print("Receive Data: " + ex.Message); 
      }
   }

0 个答案:

没有答案