C#UDP Socket没有收听回复?

时间:2012-05-04 05:19:04

标签: c# java udp client

我的一个程序出了点问题。 以下是它应该如何工作:

  1. C#Client将数据发送到Java服务器
  2. Java服务器检查数据
  3. Java服务器将命令发送回C#客户端
  4. C#Client接收数据并允许用户登录或注册
  5. 我设法直到第3步,但现在我陷入第4步。

    我在服务器和客户端以及服务器上运行了Wireshark。 所有包都正确进出。 服务器接收一个数据包并给出一个数据包。 客户给出一个并收到一个。 但是,如果我在控制台中检查netstat,我看不到打开的端口。 实际上我根本没有看到任何UDP套接字。 所以数据包进来但C#客户端似乎没有听,为什么?

    这是C#客户端。

    // Opening a socket with UDP as Protocol type
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    // The address of the server
    IPAddress[] address = Dns.GetHostAddresses("192.168.0.87");
    // The Endpoint with the port
    IPEndPoint endPoint = new IPEndPoint(address[0], 40001);
    
    // Defining the values I want
    string values = "Something I send here";
    // Encoding to byte with UTF8
    byte[] data = Encoding.UTF8.GetBytes(values);
    
    // Sending the values to the server on port 40001
    socket.SendTo(data, endPoint);
    
    // Showing what we sent
    Console.WriteLine("Sent: " + values);
    
    // Timeout for later, for now I just let the program get stuck
    // socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
    
    // Allowing the response to come in from everywhere
    EndPoint response = new IPEndPoint(IPAddress.Any, 0);
    // Buffer for server response (currently bigger then actually necessary for debugging)
    byte[] responseData = new byte[1024];
    
    //Receiving the data from the server
    socket.ReceiveFrom(responseData, ref response);
    
    // Outputing what we got, we don't even get here
    Console.WriteLine("You got: " + Encoding.UTF8.GetString(responseData));
    
    // Closing the socket
    socket.Close();
    

    对于调试,如果用户成功通过身份验证我想要发回字符串“Test”。

    这是Java服务器

    // Printing to the server that the user username logged in successfully
    System.out.println("User " + username + " logged in succesfully!");
    
    // The byte buffer for the response, for now just Test
    byte[] responseData = "Test".getBytes("UTF-8");
    // The Datagram Packet, getting IP from the received packet and port 40001
    DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length, receivePacket.getAddress(), 40001);
    // Sending the response, tried putting Thread.sleep here didn't help
    serverSocket.send(responsePacket);
    

    我希望我在接收部分对C#客户端做错了但不确定是什么,有什么想法或建议吗?

2 个答案:

答案 0 :(得分:2)

可能不是问题,但通常将UDP响应发送回原始请求的原始(源)端口。您将响应发送回固定端口。您可以尝试将Java位更改为:

DatagramPacket responsePacket = new DatagramPacket(responseData, 
     responseData.length, receivePacket.getAddress(), receivePacket.getPort());

答案 1 :(得分:1)

我相信你在客户端套接字上错过了对Bind的调用。

// Allowing the response to come in ON port 40001
EndPoint response = new IPEndPoint(IPAddress.Any, 40001);

socket.Bind(response);  // bind to port 40001 on some local address