Skip to content

Commit

Permalink
improve. make udp async socket
Browse files Browse the repository at this point in the history
  • Loading branch information
alec1o committed Jun 30, 2024
1 parent 82adb75 commit 593fa82
Showing 1 changed file with 27 additions and 21 deletions.
48 changes: 27 additions & 21 deletions src/udp/partials/UDP.ServerTo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -289,11 +291,15 @@ ref point

// publish data for a connected client
client.OnServerBuffer(ref data);

}
catch (Exception e)
{
NetlyEnvironment.Logger.Create(e);
}

AcceptUpdate();
}
}
}
}
Expand Down

0 comments on commit 593fa82

Please sign in to comment.