【发布时间】:2018-01-04 01:40:11
【问题描述】:
我创建了一个聊天应用程序,用于向与多个客户端的多播组对话发送消息。
消息必须发送到MulticastServer 并发送到组播组中的所有客户端。至此,消息完美地从客户端到达服务器。
但是当我回复客户端(甚至是简单的字符串)时,消息仅发送给发送消息的客户端,而不是发送给多播组中的所有用户。
StackTrace 没有给我任何错误,但我仍然遇到这个问题。
我给你一些重要的代码。以下是与多播服务器的连接。 DEFAULT_ADRESS 是 224.0.0.3。
socket = new MulticastSocket();
address = InetAddress.getByName(DEFAULT_ADRESS);
socket.joinGroup(address);
向 MulticastServer 发送消息的部分代码:
String messtoSendServer = utilizadorOnline.getNome() + ":" + textfieldtocomunicateGroupe.getText();
buf = messtoSendServer.getBytes();
packet = new DatagramPacket(buf, buf.length, address, DEFAULT_PORT);
try {
// userOnline_Multicast.getSocketMulti().send(packet);
socket.send(packet);
} catch (IOException ex) {
Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
}
从服务器接收消息的部分代码:
private void receberDadosServidor() throws IOException {
try {
DatagramPacket packet1 = new DatagramPacket(buf, buf.length);
socket.receive(packet1);
String received = new String(packet1.getData());
textareatoGroupChat.setText(textareatoGroupChat.getText() + "\n" + received);
} catch (IOException ex) {
Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
socket.close();
socket.leaveGroup(address);
}
这是服务器端。首先启动线程:
public void run(JTextArea txtArea) throws IOException {
new MulticastServerThread(txtArea).start();
}
还有线程本身:
public class MulticastServerThread extends Thread {
private final String DEFAULT_MULTICASTIP = "224.0.0.3";
private final int DEFAULT_MULTICASTPORT = 4446;
private final int FIVE_SECONDS =5000;
private DatagramPacket packet;
private JTextArea textA;
private boolean moreQuotes = true;
private MulticastSocket socket = null;
private InetAddress adresstoConnectMulticast = null;
public MulticastServerThread(JTextArea txt) throws IOException {
super("MulticastServerThread");
this.textA = txt;
}
@Override
public void run() {
while (true) {
try {
byte[] buf = new byte[1024];
socket = new MulticastSocket(DEFAULT_MULTICASTPORT);
adresstoConnectMulticast = InetAddress.getByName(DEFAULT_MULTICASTIP);
socket.joinGroup(adresstoConnectMulticast);
packet = new DatagramPacket(buf, buf.length, adresstoConnectMulticast, DEFAULT_MULTICASTPORT); //usado para receber um datagram do socket, o array de bytes contem dados do cliente especifico
socket.receive(packet);
String mensagem = new String(packet.getData()).trim();
textA.setText(textA.getText() + "\n\nServer Multicast Receive from User:" + mensagem +" on IP Multicast " +DEFAULT_MULTICASTIP +" | "+ DEFAULT_MULTICASTPORT);
buf = mensagem.getBytes();
InetAddress ed = packet.getAddress();
int portad = packet.getPort();
//manda de volta para o cliente.
packet = new DatagramPacket(buf, buf.length, ed, portad);
socket.send(packet);
try {
sleep((long) Math.random() * FIVE_SECONDS);
} catch (InterruptedException e) {
}
} catch (IOException ex) {
Logger.getLogger(MulticastServerThread.class.getName()).log(Level.SEVERE, null, ex);
socket.close();
}
}
}
}
【问题讨论】: