java—向多播端口发送单播数据包

l5tcr1uw  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(253)

我打开了一个多播套接字,正在接收多播消息。从这个线程看来,同一个多播套接字也应该能够接收单播消息。但是,我什么也得不到。
编辑:端口号似乎是问题所在。端口3702被ws-discovery用于单播,这与我正在尝试的操作有关。我正在追踪一个问题,其中客户端对服务的探测没有被服务的多播套接字捕获。我在windows上运行这个。
我的多播服务器:

class Server extends Thread {
MulticastSocket multicastSocket;
final Logger LOG;
final int PORT = 3702;
final String MULTICAST_ADDR = "239.255.255.250";
InetAddress multicastGroup;

public Server() {
    LOG = Logger.getLogger("Server");
    try {
        multicastGroup = InetAddress.getByName(MULTICAST_ADDR);
        multicastSocket = new MulticastSocket(PORT);
        multicastSocket.setInterface(InetAddress.getLocalHost());
        multicastSocket.joinGroup(multicastGroup);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void run() {
    while (!Global.exit) {
        byte[] buf = new byte[1000];
        DatagramPacket recv = new DatagramPacket(buf, buf.length);
        try {
            multicastSocket.receive(recv);
            String msg = new String(recv.getData(), StandardCharsets.UTF_8);
            LOG.log(Level.INFO, "got: " + msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户代码:

public void directMsgTest(){
    try {
        DatagramSocket datagramSocket = new DatagramSocket( 8080,InetAddress.getLocalHost());
        String msg = "direct msg";
        byte[] buf = msg.getBytes();
        DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), DST_PORT);
        datagramSocket.send(packet);
        datagramSocket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题