Skip to content

Commit

Permalink
impl optional message framing TcpClient
Browse files Browse the repository at this point in the history
  • Loading branch information
alec1o committed Jun 30, 2023
1 parent 9184c60 commit 5bea01a
Showing 1 changed file with 43 additions and 11 deletions.
54 changes: 43 additions & 11 deletions src/Tcp/TcpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,23 @@ namespace Netly
{
public class TcpClient : Client
{
public TcpClient() { }

internal TcpClient(string uuid, Socket socket)
/// <summary>
/// TCP client: Instance
/// </summary>
/// <param name="messageFraming">true: netly will use its own message framing protocol, set false if your server is not netly and you want to communicate with other libraries</param>
public TcpClient(bool messageFraming)
{
MessageFraming = messageFraming;
}

internal TcpClient(string uuid, Socket socket, bool messageFramming)
{
UUID = uuid;
m_socket = socket;
MessageFraming = messageFramming;
Host = new Host(socket.RemoteEndPoint);
}
}

public override void Open(Host host)
{
Expand Down Expand Up @@ -62,15 +71,22 @@ protected override void Receive()

ThreadPool.QueueUserWorkItem(_ =>
{
_package.Output((buffer) =>
if (MessageFraming)
{
(string name, byte[] buffer) content = MessageParser.Verify(buffer);
_package.Output((buffer) =>
{
(string name, byte[] buffer) content = MessageParser.Verify(buffer);

if (content.buffer == null)
onDataHandler?.Invoke(null, buffer);
else
onEventHandler?.Invoke(null, (content.name, content.buffer));
});
if (content.buffer == null)
{
onDataHandler?.Invoke(null, buffer);
}
else
{
onEventHandler?.Invoke(null, (content.name, content.buffer));
}
});
}

while (m_socket != null)
{
Expand All @@ -87,7 +103,23 @@ protected override void Receive()
byte[] buffer = new byte[_length];
Array.Copy(_buffer, 0, buffer, 0, buffer.Length);

_package.Input(buffer);
if (MessageFraming)
{
_package.Input(buffer);
}
else
{
(string name, byte[] buffer) content = MessageParser.Verify(buffer);

if (content.buffer == null)
{
onDataHandler?.Invoke(null, buffer);
}
else
{
onEventHandler?.Invoke(null, (content.name, content.buffer));
}
}
}
catch
{
Expand Down

0 comments on commit 5bea01a

Please sign in to comment.