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 @   luckyangg  阅读(748)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示