From 530bf8078e6e2289795af0b4e0c0d91cfcaa6111 Mon Sep 17 00:00:00 2001 From: redkale Date: Tue, 7 Feb 2023 17:34:33 +0800 Subject: [PATCH] =?UTF-8?q?udp=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../redkale/net/AsyncNioUdpConnection.java | 24 ++++++++++++------- .../net/AsyncNioUdpProtocolServer.java | 3 +++ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/redkale/net/AsyncNioUdpConnection.java b/src/main/java/org/redkale/net/AsyncNioUdpConnection.java index a978b143a..1e88b3245 100644 --- a/src/main/java/org/redkale/net/AsyncNioUdpConnection.java +++ b/src/main/java/org/redkale/net/AsyncNioUdpConnection.java @@ -150,24 +150,30 @@ class AsyncNioUdpConnection extends AsyncNioConnection { @Override protected int implWrite(ByteBuffer src) throws IOException { - long now = System.currentTimeMillis(); - //发送过频会丢包 + if (clientMode) { + long now = System.currentTimeMillis(); if (this.writeTime + 1 > now) { - Utility.sleep(1); + Utility.sleep(1); //发送过频会丢包 this.writeTime = System.currentTimeMillis(); } else { this.writeTime = now; } return this.channel.send(src, remoteAddress); } else { - if (udpServerChannel.writeTime + 1 > now) { - Utility.sleep(1); - udpServerChannel.writeTime = System.currentTimeMillis(); - } else { - udpServerChannel.writeTime = now; + udpServerChannel.writeLock.lock(); + try { + long now = System.currentTimeMillis(); + if (udpServerChannel.writeTime + 1 > now) { + Utility.sleep(1); //发送过频会丢包 + udpServerChannel.writeTime = System.currentTimeMillis(); + } else { + udpServerChannel.writeTime = now; + } + return this.channel.send(src, remoteAddress); + } finally { + udpServerChannel.writeLock.unlock(); } - return this.channel.send(src, remoteAddress); } } diff --git a/src/main/java/org/redkale/net/AsyncNioUdpProtocolServer.java b/src/main/java/org/redkale/net/AsyncNioUdpProtocolServer.java index 35c03a31d..b13aaa6f7 100644 --- a/src/main/java/org/redkale/net/AsyncNioUdpProtocolServer.java +++ b/src/main/java/org/redkale/net/AsyncNioUdpProtocolServer.java @@ -12,6 +12,7 @@ import java.nio.channels.*; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.LongAdder; +import java.util.concurrent.locks.ReentrantLock; import java.util.function.*; import java.util.logging.Level; import org.redkale.boot.Application; @@ -240,6 +241,8 @@ class AsyncNioUdpProtocolServer extends ProtocolServer { ByteBufferPool unsafeBufferPool; + final ReentrantLock writeLock = new ReentrantLock(); + volatile long writeTime; ConcurrentHashMap connections = new ConcurrentHashMap<>();