嘿,我正在尝试用 Java 编写一个聊天服务器多播程序,但它没有按预期工作。
我有两个文件,ChatClient.java 和 ChatServer.java(下面的代码)。
ChatClient 向服务器发送一条消息,然后服务器将接收消息并将其打印出来,但它没有收到消息,有人能注意到为什么吗?
客户代码:
public class ChatClient {
public static void main(String args[]) throws Exception {
MulticastSocket chat = new MulticastSocket(8885);
InetAddress group = InetAddress.getByName("224.2.2.5");
chat.joinGroup(group);
String msg = "";
System.out.println("Type a message for the server:");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
msg = br.readLine();
DatagramPacket data = new DatagramPacket(msg.getBytes(), 0, msg.length(), group, 8885);
chat.send(data);
chat.close();
}
}
服务器代码:
public class ChatServer {
public static void main(String args[]) throws Exception {
MulticastSocket server = new MulticastSocket(8885);
InetAddress group = InetAddress.getByName("224.2.2.5");
//getByName - returns IP address of the given host
server.joinGroup(group);
boolean infinite = true;
/* Server continually receives data and prints them */
while(infinite) {
byte buf[] = new byte[1024];
DatagramPacket data = new DatagramPacket(buf, buf.length);
server.receive(data);
String msg = new String(data.getData()).trim();
System.out.println(msg);
}
server.close();
}
}