我的程序无法正常运行。问题是第二个客户端无法看到第一个消息。我认为问题在于循环。只是不读取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);
}
}
}
}
}
答案 0 :(得分:1)
假设您在聊天的两端使用相同的程序,则不会发生任何事情。在编写任何内容之前,每个实例都通过读取套接字来启动,因此它将永远阻塞。
没有任何实例可以写入套接字的位置。
请注意,套接字编程通常需要多个线程,因为事情是在至少两个&#34;信道上异步发生的。 (用户交互和套接字I / O)。有关如何编写网络代码的完整说明远远超出了StackOverflow的设计目的。