从java udp编程一切都工作正常,除了没有检测到响应客户端的服务器。即向服务器发送数据是好的,服务器接收到数据并响应客户端。问题是数据没有接收到客户端。我使用的本地端口是 501 服务器监听端口是 500,我将数据发送到 500 到服务器并在客户端等待 501 的连接。代码可以说明这一点:这是接收线程..不知道哪里出错了!注意我使用的是在线服务器。
String myipAddress = "10.100.69.174";
String SendingIp = "108.163.180.54";
String sendinPort = "500";
String myRecievePortNo="501";
public void run()
{
try {
recievingSocket = new DatagramSocket(Integer.parseInt(myRecievePortNo), InetAddress.getByName(myipAddress));
while (true)
{
byte[] data = new byte[1024];
DatagramPacket recievingPacket = new DatagramPacket(data, data.length);
recievingSocket.receive(recievingPacket);
String mydata = new String(data, 0, data.length);
System.out.printf("Hello recieve"+mydata);
}
}
}
catch (Exception EX)
{
JOptionPane.showMessageDialog(null, "Error Message" + EX, "Error", JOptionPane.ERROR_MESSAGE);
}
}
//this section is call when user click the send button
public void sendData(String toServer) {
try
{
DatagramSocket sendingSocket = new DatagramSocket(Integer.parseInt(myRecievePortNo));
byte[] data = toServer.getBytes();
DatagramPacket sendingPacket = new DatagramPacket(data, data.length, InetAddress.getByName(SendingIp), Integer.parseInt(sendinPort));
sendingSocket.send(sendingPacket);
sendingSocket.close();
}
catch (Exception EX)
{
JOptionPane.showMessageDialog(null, "Sending Error :" + EX, "Error", JOptionPane.ERROR_MESSAGE);
}
}