1.服務端代碼:
package com.jidongcloud.bean;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.UUID;
/**
* ClassName:CTRL+ALT+L是格式對齊。
* PackageName:com.jidongcloud.bean
* Description: socket 之局域網搜索案列 (廣播局域網信息) ----提供者
* 優秀博文 : https://blog.csdn.net/nicolelili1/article/details/103956181?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-2
*
* @date:2020/5/15 17:21
* @author:robin
*/
public class UDPBroadcastProvider {
public static void main(String[] args) throws IOException {
// 生成一份唯一標識
String sn = UUID.randomUUID().toString();
Provider provider = new Provider(sn);
provider.start();
// 讀取任意鍵盤信息後可以退出
//noinspection ResultOfMethodCallIgnored
System.in.read();
provider.exit();
}
private static class Provider extends Thread {
private final String sn;
private boolean done = false;
private DatagramSocket ds = null;
public Provider(String sn) {
super();
this.sn = sn;
}
@Override
public void run() {
super.run();
System.out.println("UDPProvider Started.");
try {
// 監聽20000 端口
ds = new DatagramSocket(20000);
while (!done) {
// 構建接收實體
final byte[] buf = new byte[512];
DatagramPacket receivePack = new DatagramPacket(buf, buf.length);
// 接收 ,這裏會一直出現阻塞現象,那麼當什麼時候結束呢? ds=null時候,這時候會走try-catch異常,結束線程。
ds.receive(receivePack);
// 打印接收到的信息與發送者的信息
// 發送者的IP地址
String ip = receivePack.getAddress().getHostAddress();
int port = receivePack.getPort();
int dataLen = receivePack.getLength();
String data = new String(receivePack.getData(), 0, dataLen);
////這行代碼在啓動provider時候應該輸出內容
System.out.println("UDPProvider receive form ip:" + ip + "\tport:" + port + "\tdata:" + data);
// 解析端口號
int responsePort = MessageCreator.parsePort(data);
if (responsePort != -1) {
// 構建一份回送數據
String responseData = MessageCreator.buildWithSn(sn);
byte[] responseDataBytes = responseData.getBytes();
// 直接根據發送者構建一份回送信息
DatagramPacket responsePacket = new DatagramPacket(responseDataBytes,
responseDataBytes.length, receivePack.getAddress(), responsePort);
ds.send(responsePacket);
}
}
} catch (Exception ignored) {
} finally {
close();
}
// 完成
System.out.println("UDPProvider Finished.");
}
private void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
/**
* 提供結束
*
*/
void exit() {
done = true;
close();
}
}
}
2.客戶端代碼
package com.jidongcloud.bean;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* ClassName:UDPBroadcastSearcher
* PackageName:com.jidongcloud.bean
* Description: ----搜尋者
*
* @date:2020/5/15 23:23
* @author:robin
*/
public class UDPBroadcastSearcher {
/**
* * UDP 搜索者,用於搜索服務支持方
*
*/
private static final int LISTEN_PORT = 30000;
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("UDPSearcher Started.");
Listener listener = listen();
sendBroadcast();
// 讀取任意鍵盤信息後可以退出
//noinspection ResultOfMethodCallIgnored
System.in.read();
List<Device> devices = listener.getDevicesAndClose();
for (Device device : devices) {
System.out.println("Device:" + device.toString());
}
// 完成
System.out.println("UDPSearcher Finished.");
}
private static Listener listen() throws InterruptedException {
System.out.println("UDPSearcher start listen.");
CountDownLatch countDownLatch = new CountDownLatch(1);
Listener listener = new Listener(LISTEN_PORT, countDownLatch);
listener.start();
countDownLatch.await();
return listener;
}
private static void sendBroadcast() throws IOException {
System.out.println("UDPSearcher sendBroadcast started.");
// 作爲搜索方,讓系統自動分配端口
DatagramSocket ds = new DatagramSocket();
// 構建一份請求數據
String requestData = MessageCreator.buildWithPort(LISTEN_PORT);
byte[] requestDataBytes = requestData.getBytes();
// 直接構建packet
DatagramPacket requestPacket = new DatagramPacket(requestDataBytes,
requestDataBytes.length);
// 20000端口, 廣播地址
requestPacket.setAddress(InetAddress.getByName("255.255.255.255"));
requestPacket.setPort(20000);
// 發送
ds.send(requestPacket);
ds.close();
// 完成
System.out.println("UDPSearcher sendBroadcast finished.");
}
private static class Device {
final int port;
final String ip;
final String sn;
private Device(int port, String ip, String sn) {
this.port = port;
this.ip = ip;
this.sn = sn;
}
@Override
public String toString() {
return "Device{" + "port=" + port + ", ip='" + ip + '\'' + ", sn='" + sn + '\'' + '}';
}
}
private static class Listener extends Thread {
private final int listenPort;
private final CountDownLatch countDownLatch;
private final List<Device> devices = new ArrayList<>();
private boolean done = false;
private DatagramSocket ds = null;
public Listener(int listenPort, CountDownLatch countDownLatch) {
super();
this.listenPort = listenPort;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
super.run();
// 通知已啓動
countDownLatch.countDown();
try {
// 監聽回送端口
ds = new DatagramSocket(listenPort);
while (!done) {
// 構建接收實體
final byte[] buf = new byte[512];
DatagramPacket receivePack = new DatagramPacket(buf, buf.length);
// 接收
ds.receive(receivePack);
// 打印接收到的信息與發送者的信息
// 發送者的IP地址
String ip = receivePack.getAddress().getHostAddress();
int port = receivePack.getPort();
int dataLen = receivePack.getLength();
String data = new String(receivePack.getData(), 0, dataLen);
System.out.println("UDPSearcher receive form ip:" + ip + "\tport:" + port + "\tdata:" + data);
String sn = MessageCreator.parseSn(data);
if (sn != null) {
Device device = new Device(port, ip, sn);
devices.add(device);
}
}
} catch (Exception ignored) {
} finally {
close();
}
System.out.println("UDPSearcher listener finished.");
}
private void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
List<Device> getDevicesAndClose() {
done = true;
close();
return devices;
}
}
}
3.測試信息
開啓服務端:
開啓客戶端:
再看服務端信息: