How do I make my multicast program work between computers on different networks?

廉价感情. 提交于 2019-12-06 12:39:00

问题


I made a little chat applet using multicast. It works fine between computers on the same network, but fails if the computers are on different networks. Why is this?

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ClientA extends JApplet implements ActionListener, Runnable {

 JTextField tf;
JTextArea ta;
 MulticastSocket socket;
 InetAddress group;
 String name="";

public void start()  {
    try {
socket = new MulticastSocket(7777);
group = InetAddress.getByName("233.0.0.1");
socket.joinGroup(group); 
socket.setTimeToLive(255);
Thread th = new Thread(this);
th.start();
name =JOptionPane.showInputDialog(null,"Please enter your name.","What is your name?",JOptionPane.PLAIN_MESSAGE);
tf.grabFocus();
    }catch(Exception e) {e.printStackTrace();}
}

public void init() {

JPanel p = new JPanel(new BorderLayout());
ta = new JTextArea();
ta.setEditable(false);
ta.setLineWrap(true);
JScrollPane sp = new JScrollPane(ta);
p.add(sp,BorderLayout.CENTER);
JPanel p2 = new JPanel();
tf = new JTextField(30);
tf.addActionListener(this);
p2.add(tf);
JButton b = new JButton("Send");
b.addActionListener(this);
p2.add(b);
p.add(p2,BorderLayout.SOUTH);
add(p);

}

public void actionPerformed(ActionEvent ae) {
String message = name+":"+tf.getText();
tf.setText("");
tf.grabFocus();
byte[] buf = message.getBytes();
DatagramPacket packet = new DatagramPacket(buf,buf.length, group,7777);
try {
socket.send(packet);
}
catch(Exception e) {}
}



public void run() {
while(true) {
byte[] buf = new byte[256];
String received = "";
  DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
            socket.receive(packet);
             received = new String(packet.getData()).trim();
}
catch(Exception e) {}
ta.append(received +"\n");
ta.setCaretPosition(ta.getDocument().getLength());
}
}

}

回答1:


Most routers (routing IPv4) are configured to not support multicasting.

http://www.ibiblio.org/pub/Linux/docs/howto/other-formats/html_single/Multicast-HOWTO.html

For multicasting to work across networks, the router(s) involved would need to be configured to support it. IPv6 it's required, but IPv4 it is optional and normally not done.



来源:https://stackoverflow.com/questions/2656590/how-do-i-make-my-multicast-program-work-between-computers-on-different-networks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!