我的程序无法正常运行。问题是第二个客户端看不到来自第一个客户端的消息。我认为问题出在while循环中。只是不从 IP 地址读取。你能帮助我吗?先感谢您。
package multicastchat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MulticastChat {
int chatRoom = 0;
int port = 0;
String ipAdress = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public MulticastChat(){
}
public void choosingChatRoom() throws IOException{
while (!(chatRoom > 0 && chatRoom < 5)) {
System.out.println(
"We have four chat rooms, choose one of them (1, 2, 3, 4)");
chatRoom = Integer.valueOf(br.readLine());
switch (chatRoom) {
case 1:
port = 4441;
ipAdress = "230.0.0.1";
break;
case 2:
port = 4442;
ipAdress = "230.0.0.2";
break;
case 3:
port = 4443;
ipAdress = "230.0.0.3";
break;
case 4:
port = 4444;
ipAdress = "230.0.0.4";
break;
default:
System.out.println("Sorry, but we haven't this room, try another room");
this.choosingChatRoom();
break;
}
System.out.println("Welcome to room " + chatRoom);
}
}
public static void main(String[] args) throws IOException {
MulticastChat mc = new MulticastChat();
mc.choosingChatRoom();
MulticastSocket socket = new MulticastSocket(mc.port);
InetAddress address = InetAddress.getByName(mc.ipAdress);
socket.joinGroup(address);
DatagramPacket outMessage;
DatagramPacket inMessage;
String userInput;
while (true) {
//Receiving message
inMessage = new DatagramPacket(new byte[4096], 4096);
inMessage.setLength(inMessage.getData().length);
socket.receive(inMessage);
String received = new String(
inMessage.getData(), 0, inMessage.getLength());
System.out.println(received);
//Sending message
if ((userInput = mc.br.readLine()) != null) {
if (userInput.equals("quit")) {
System.out.println("Bye, see you later ^_^");
socket.leaveGroup(address);
socket.close();
System.exit(0);
} else {
byte[] buff = userInput.getBytes();
outMessage =
new DatagramPacket(buff, buff.length, address, mc.port);
socket.send(outMessage);
}
}
}
}
}