當我使用本地主機上的客戶端和服務器測試它的作品時。但是隨後我將客戶端和服務器拆分爲具有不同IP地址的不同機器,現在客戶端沒有收到數據包。任何人都可以發現這個問題與我的代碼:Java - 通過UDP連接將消息從一臺PC發送到另一臺PC
客戶:
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嗎? – roni 2012-03-03 19:19:11
服務器和客戶端是否位於同一網絡上?如果他們不是,他們在NAT設備後面嗎?問題可能不在於您的代碼,而是與網絡的配置方式有關。 – smessing 2012-03-03 19:21:18
奇數,這是一個公共IP地址。防火牆規則可能會阻止您的UDP通信,您可能需要使用數據包嗅探器進行驗證,或與您的服務器管理員聯繫。 – Perception 2012-03-03 19:22:45