将udp数据报包广播到连接的客户端不工作

时间:2015-12-03 10:00:49

标签: java networking udp serversocket

我有多个发送器配置为在接收到服务器通过本地端口5255发送的广播数据包时发回响应,远程端口5252包含字符串" AST显示我\ 0" (如发射器'手册中所述)。这应该可以帮助我扫描本地网络中的所有发射器。我已经实现了一个服务器端代码来广播该字符串消息,但是当我运行代码时,它在以下行代码中有一个错误:

  socket.receive(packet1);

我真的不知道我在这段代码中做错了什么或遗漏了什么。任何帮助将不胜感激。

注意:如果有帮助:发射器' IP地址为192.168.40。*;服务器IP地址为192.168.40.254。

提前致谢!!

以下是代码:

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);

        //broadcast the string to the transmitters
        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);
        System.out.println("Sent packet : " +packet.getData().toString());

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

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

}

以下是错误:

Sent packet : [B@70dea4e
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:32)

1 个答案:

答案 0 :(得分:0)

  

发射器' IP地址为192.168.40。*

广播到192.168.40.255