我的一个程序有点问题。这是它应该如何工作的:
- C#客户端向Java服务器发送数据
- Java 服务器检查数据
- Java 服务器向 C# 客户端发回命令
- C#客户端接收数据并使用户能够登录或注册
我设法到达第 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();
For debugging, if the user authenticated successfully I want to send the string "Test" back.
Here is the Java server
// 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);
I expect that I did something wrong with the C# client at the receive part but not sure what, any ideas or suggestions?