Java发送UDP广播并同时接收设备返回信息

使用场景:因为某项目涉及到一个厂商的异步投屏设备,然后获取设备的CODE需要在同局域网使用UDP发送广播,发送完广播后会收到设备返回的相关信息数据。


import org.slf4j.Logger; import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @Author lingyang
 * @Description UDP广播及反馈的消息接受
 * @Date 2021/8/11 17:32
 * @Version 1.0
 */
public class SendUDP
{
    public static void main(String[] args) throws Exception
    {

        Logger logger = LoggerFactory.getLogger(SendUDP.class);

        // Use this port to send broadcast packet
        @SuppressWarnings("resource")
        final DatagramSocket detectSocket = new DatagramSocket(18880);

        // Send packet thread
        new Thread(() ->
        {
            logger.info("Send thread started.");
            while (true)
            {
                try
                {
                    byte[] buf;
                    int packetPort = 18880;

                    // Broadcast address
                    InetAddress hostAddress = InetAddress.getByName("192.168.50.1");
                    BufferedReader stdin = new BufferedReader(
                            new InputStreamReader(System.in));
                    String outMessage = stdin.readLine();

                    if (outMessage.equals("bye"))
                        break;
                    buf = outMessage.getBytes();
                    logger.info("Send {} to {}", outMessage, hostAddress);
                    // Send packet to hostAddress:9999, server that listen
                    // 9999 would reply this packet
                    DatagramPacket out = new DatagramPacket(buf,
                            buf.length, hostAddress, packetPort);
                    detectSocket.send(out);
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }).start();

        // Receive packet thread.
        new Thread(() ->
        {
            logger.info("Receive thread started.");
            while (true)
            {
                byte[] buf = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                try
                {
                    detectSocket.receive(packet);
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
                String rcvd = "Received from " + packet.getSocketAddress() + ", Data="
                        + new String(packet.getData(), 0, packet.getLength());
                logger.info(rcvd);
            }
        }).start();
    }
}
posted @ 2021-08-13 15:03  luckyangg  阅读(737)  评论(0编辑  收藏  举报