『LoG』☠ 𝓣 𝓐 𝓛 𝓔 𝓝 𝓣 ♚
❔ asynchronous coding
private void TrySend()
{
if (!IsConnected)
return;
bool isProcess = true;
while (isProcess)
{
isProcess = false;
lock (_sendLock)
{
// Is previous socket send in progress?
if (_sendBufferFlush.IsEmpty)
{
// Swap flush and main buffers
_sendBufferFlush = Interlocked.Exchange(ref _sendBufferMain, _sendBufferFlush);
_sendBufferFlushOffset = 0;
// Check if the flush buffer is empty
if (_sendBufferFlush.IsEmpty)
{
// End sending process
_sending = false;
return;
}
}
else
return;
}
try
{
// Async write with the write handler
_sendEventArg.SetBuffer(_sendBufferFlush.Data, _sendBufferFlushOffset, _sendBufferFlush.Size - _sendBufferFlushOffset);
if (!Socket.SendAsync(_sendEventArg))
isProcess = ProcessSend(_sendEventArg);
}
catch (ObjectDisposedException obj)
{
Console.WriteLine(obj);
}
}
}
31 replies
❔ asynchronous coding
public virtual bool SendAsync(byte[] buffer, int offset, int size)
{
if (!IsConnected)
return false;
if (size == 0)
return true;
lock (_sendLock)
{
// Fill the main send buffer
_sendBufferMain.Append(buffer, offset, size);
// Avoid multiple send handlers
if (_sending)
return true;
_sending = true;
// Try to send the main buffer
Task.Factory.StartNew(TrySend);
}
return true;
}
31 replies
❔ asynchronous coding
public virtual void TransferToClientAsync()
{
try
{
var transferBuffers = ClientSecurity.TransferOutgoing();
if (transferBuffers == null) return;
foreach (var (transferBuffer, _) in transferBuffers)
{
SendAsync(transferBuffer.Buffer, transferBuffer.Offset, transferBuffer.Size);
}
}
catch (Exception)
{
Disconnect();
}
}
31 replies
❔ asynchronous coding
public void SendNotice(string notice, bool useAsync = true)
{
Packet packet = new Packet(0x300C);
packet.WriteValue<ushort>(3100);
packet.WriteValue<byte>(1);
packet.WriteValue<string>(notice);
ClientSecurity.Send(packet);
packet = new Packet(0x300C);
packet.WriteValue<ushort>(3100);
packet.WriteValue<byte>(2);
packet.WriteValue<string>(notice);
ClientSecurity.Send(packet);
if (useAsync)
{
TransferToClientAsync();
}
else
{
TransferToClient();
}
}
31 replies
❔ asynchronous coding
public Task<PacketResult> Handle(Session session, Packet packet)
{
if (Settings.ConnectionLimit)
{
session.SendNotice(NoticeClass.ConnectionLimit);
return Task.FromResult(PacketResult.Ignore);
}
return Task.FromResult(PacketResult.None);
}
One of the methods I use is as follows
I preferred this method because more than one packet is sent for a user and many packets usually contain some blocking.
31 replies