Broadcasting packet to client not working in java

痴心易碎 提交于 2019-12-02 15:32:49

问题


I have multiple transmitters configured to send back a response when they receive a broadcast packet sent from a server through local port 5255, remote port 5252 containing the string "AST show me\0" (as stated in transmitters' manual). This should help me to scan for all the transmitters within the local network. I have implemented a server side code to broadcast that string message, but when I run the code , it have a bug at the following line code :

  socket.receive(packet1);

I don't really know what I am doing wrong or missing in this code. Any help will be greatly appreciated.

Note: If it might help : The transmitters' IP address are from 192.168.40.* ; and the server IP address is 192.168.40.254.

Thanks in advance !!

Here is the code :

package socket_test;

import java.io.*;
import java.net.*;


public class Server_UDP_Broadcast {

//@SuppressWarnings("null")
public static void main(String[] args) {
    // TODO Auto-generated method stub

    DatagramSocket socket = null;

    try{
        socket = new DatagramSocket(5255);
        socket.setSoTimeout(10000);

        String str = "AST show me\0";
        byte[] buf = new byte[256];
        buf = str.getBytes();
        InetAddress group = InetAddress.getByName("255.255.255.255");
        DatagramPacket packet;
        packet = new DatagramPacket(buf, buf.length, group, 5252);
        socket.send(packet);


        // receive answer and display
        byte[] buf1 = new byte[1024];
        DatagramPacket packet1 = new DatagramPacket(buf1, buf1.length); 
        socket.receive(packet1);   
        String received = new String(packet1.getData(), 0, packet1.getLength());
        System.out.println("Answer from I-Lite :: " + received);          

    }
    catch (IOException e) {
        e.printStackTrace();
    }

}

}

Here are the bugs :

java.net.SocketTimeoutException: Receive timed out
at java.net.DualStackPlainDatagramSocketImpl.socketReceiveOrPeekData   (Native Method)
at java.net.DualStackPlainDatagramSocketImpl.receive0(Unknown Source)
at java.net.AbstractPlainDatagramSocketImpl.receive(Unknown Source)
at java.net.DatagramSocket.receive(Unknown Source)
at socket_test.Server_UDP_Broadcast.main(Server_UDP_Broadcast.java:31)

Here is the screenshots from from wireshark:

Captured packet's details

WireShark's Screenhot

来源:https://stackoverflow.com/questions/34047668/broadcasting-packet-to-client-not-working-in-java

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