From 593fa82fa59a68fbf053384b24f2746d6ed4b24d Mon Sep 17 00:00:00 2001 From: "Alecio Furanze (Ale)" Date: Sun, 30 Jun 2024 20:33:22 +0200 Subject: [PATCH] improve. make udp async socket --- src/udp/partials/UDP.ServerTo.cs | 48 ++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/src/udp/partials/UDP.ServerTo.cs b/src/udp/partials/UDP.ServerTo.cs index 86cd096b..1678448f 100644 --- a/src/udp/partials/UDP.ServerTo.cs +++ b/src/udp/partials/UDP.ServerTo.cs @@ -235,38 +235,40 @@ private void Send(Host host, byte[] bytes) private void InitAccept() { - new Thread(AcceptJob) + var length = (int)_socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); + var buffer = new byte[length > 0 ? length : 4096]; + var remoteEndPoint = Host.EndPoint; + + AcceptUpdate(); + + void AcceptUpdate() { - IsBackground = true, - Priority = ThreadPriority.Highest - }.Start(); - } + if (!IsOpened) + { + Close(); + return; + } - private void AcceptJob() - { - var length = (int)_socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); - var buffer = new byte[length]; - var point = Host.EndPoint; + _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEndPoint, AcceptCallback, null); + } - while (IsOpened) + void AcceptCallback(IAsyncResult result) + { try { - var size = _socket.ReceiveFrom - ( - buffer, - 0, - buffer.Length, - SocketFlags.None, - ref point - ); + var size = _socket.EndReceiveFrom(result, ref remoteEndPoint); - if (size <= 0) continue; + if (size <= 0) + { + AcceptUpdate(); + return; + } var data = new byte[size]; Array.Copy(buffer, 0, data, 0, data.Length); - var newHost = new Host(point); + var newHost = new Host(remoteEndPoint); // Find a client connected user by endpoint connection (IP, PORT) var client = Clients.FirstOrDefault(x => Host.Equals(newHost, x.Host)); @@ -289,11 +291,15 @@ ref point // publish data for a connected client client.OnServerBuffer(ref data); + } catch (Exception e) { NetlyEnvironment.Logger.Create(e); } + + AcceptUpdate(); + } } } }