Performance: frame broadcasts once, Socket.Select instead of fixed sleep, reuse message list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+17
-6
@@ -101,6 +101,7 @@ public sealed class Connection
|
||||
DateTime closeDeadline;
|
||||
string closingReason;
|
||||
readonly byte[] readBuffer = new byte[64 * 1024];
|
||||
readonly List<Message> received = new();
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
int count;
|
||||
|
||||
@@ -113,9 +114,16 @@ public sealed class Connection
|
||||
RemoteAddress = client.Client.RemoteEndPoint?.ToString() ?? "?";
|
||||
}
|
||||
|
||||
/// <summary>Socket zum Warten auf Daten (Socket.Select im Server-Loop).</summary>
|
||||
public Socket Socket => client.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Neue Nachrichten. Die Liste wird beim nächsten Aufruf wiederverwendet (keine Allokation pro Durchlauf).
|
||||
/// </summary>
|
||||
public List<Message> Poll()
|
||||
{
|
||||
var messages = new List<Message>();
|
||||
var messages = received;
|
||||
messages.Clear();
|
||||
if (IsClosed) return messages;
|
||||
if (closing)
|
||||
{
|
||||
@@ -124,12 +132,13 @@ public sealed class Connection
|
||||
}
|
||||
try
|
||||
{
|
||||
if (client.Client.Poll(0, SelectMode.SelectRead) && client.Available == 0)
|
||||
if (client.Available == 0)
|
||||
{
|
||||
Close("Connection closed");
|
||||
// Getrennt? "lesbar, aber keine Daten" = Gegenseite hat geschlossen
|
||||
if (client.Client.Poll(0, SelectMode.SelectRead) && client.Available == 0) Close("Connection closed");
|
||||
return messages;
|
||||
}
|
||||
while (stream.DataAvailable)
|
||||
while (client.Available > 0)
|
||||
{
|
||||
int read = stream.Read(readBuffer, 0, readBuffer.Length);
|
||||
if (read <= 0) break;
|
||||
@@ -145,12 +154,14 @@ public sealed class Connection
|
||||
return messages;
|
||||
}
|
||||
|
||||
public void Send(MsgType type, byte[] payload = null)
|
||||
public void Send(MsgType type, byte[] payload = null) => SendFrame(Wire.Frame(type, payload));
|
||||
|
||||
/// <summary>Fertig gerahmte Nachricht senden (Broadcast: einmal rahmen, an alle schicken).</summary>
|
||||
public void SendFrame(byte[] frame)
|
||||
{
|
||||
if (IsClosed || closing) return;
|
||||
try
|
||||
{
|
||||
byte[] frame = Wire.Frame(type, payload);
|
||||
stream.Write(frame, 0, frame.Length);
|
||||
}
|
||||
catch (Exception e)
|
||||
|
||||
Reference in New Issue
Block a user