pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-ip</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
start server and receive msg
@Service
@Slf4j
public class UdpServer implements ApplicationRunner, ServletContextListener {
private Logger logger = LoggerFactory.getLogger(UdpServer.class);
public static final int MAX_UDP_DATA_SIZE = 4096;
public static final int UDP_PORT = 443;
public static DatagramPacket packet = null;
public static DatagramSocket socket = null;
@Override
public void run(ApplicationArguments arguments) {
try {
new Thread(new UdpProcess(UDP_PORT)).start();
}catch (Exception e) {
e.printStackTrace();
}
}
class UdpProcess implements Runnable {
public UdpProcess(final int port) throws SocketException,InterruptedException {
socket = new DatagramSocket(port);
}
@Override
public void run() {
while (true) {
byte[] buffer = new byte[MAX_UDP_DATA_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(packet);
new Thread(new Process(packet)).start();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Process implements Runnable {
public Process(DatagramPacket packet) throws IOException, InterruptedException {
byte[] buffer = packet.getData();
String str = new String(buffer, "GBK").trim();
JSONObject jj = JSON.parseObject(str);
System.out.println(jj);
}
@Override
public void run() {
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
logger.info("========UDPListener摧毁=========");
}
}
send msg
UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", 10000);
JSONObject j = new JSONObject();
j.put("ids", ids);
try {
handler.handleMessage(MessageBuilder.withPayload(j.toString()).build());
} catch (Error e) {
log.info("");
}
|