package com.ruoyi.Dzp; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; /** One exchange owns its channel, selector, receive buffer and peer address. */ public class MyUdpSocket implements AutoCloseable { private final DatagramChannel channel; private final Selector selector; private int clientPort; private String clientIp; private final ByteBuffer receiveBuffer = ByteBuffer.allocate(1280); public MyUdpSocket(int port) throws IOException { channel = DatagramChannel.open(); Selector opened = null; try { opened = Selector.open(); channel.configureBlocking(false); channel.bind(new InetSocketAddress(port)); channel.register(opened, SelectionKey.OP_READ); selector = opened; } catch (IOException | RuntimeException failure) { if (opened != null) { try { opened.close(); } catch (IOException close) { failure.addSuppressed(close); } } try { channel.close(); } catch (IOException close) { failure.addSuppressed(close); } throw failure; } } public final void send(String ip, int port, byte[] buffer, int size) throws IOException { channel.send(ByteBuffer.wrap(buffer, 0, size), new InetSocketAddress(ip, port)); } @Override public final void close() throws IOException { try { selector.close(); } finally { channel.close(); } } public final int get_client_port() { return clientPort; } public final String get_client_ip() { return clientIp; } public final void get_receive_buffer(byte[] buffer) { get_receive_packet(buffer, buffer.length); } public final int receive() { try { receiveBuffer.clear(); if (selector.select(10) != 0) { var keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (!key.isValid() || !key.isReadable()) continue; InetSocketAddress peer = (InetSocketAddress) channel.receive(receiveBuffer); if (peer != null) { clientIp = peer.getAddress().getHostAddress(); clientPort = peer.getPort(); return receiveBuffer.position(); } } } return 0; } catch (IOException e) { throw new java.io.UncheckedIOException("LED receive failed", e); } } public final void get_receive_packet(byte[] packet, int size) { System.arraycopy(receiveBuffer.array(), 0, packet, 0, size); } }