【发布时间】:2012-03-03 18:54:28
【问题描述】:
当我在 localhost 上使用客户端和服务器进行测试时,它的工作原理。但是后来我将客户端和服务器拆分到具有不同 IP 地址的不同机器上,现在客户端没有接收到数据包。谁能发现我的代码的问题:
客户:
class Csimudp {
public static DatagramSocket ds;
public static byte buffer[] = new byte[1024];
public static void Myclient() throws Exception {
while (true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
}
}
public static void main(String args[]) throws Exception {
System.out.println("for quitting client press ctrl+c");
ds = new DatagramSocket(777);
Myclient();
}
}
服务器:
class Ssimudp {
public static DatagramSocket ds;
public static byte buffer[] = new byte[1024];
public static void MyServer() throws Exception {
int pos = 0;
while (true) {
int c = System.in.read();
switch (c) {
case '~':
System.out.println("\n Quits");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer, pos, InetAddress
.getByName("117.201.5.150"), 777));
pos = 0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void main(String args[]) throws Exception {
System.out.println("server ready....\n please type here");
ds = new DatagramSocket(888);
MyServer();
}
}
【问题讨论】:
-
代码对我来说看起来不错,你能从服务器机器 ping 到 117.201.5.150 吗?
-
服务器和客户端是否在同一个网络上?如果不是,它们是否位于 NAT 设备后面?问题可能不在于您的代码,而在于网络的配置方式。
-
奇怪,这是一个公共 IP 地址。防火墙规则可能会阻止您的 UDP 通信,您可能需要使用数据包嗅探器进行验证,或联系您的服务器管理员。
标签: java networking udp