Netly version 4 is now available! Experience the new way of interacting with Netly. See more
|
⭐ Your star on Netly brightens our journey and makes a real impact! |
powered by ALEC1O
Get basic information about this project called Netly
| Overview |
Netly is a robust C# socket library designed to streamline network communication. It offers comprehensive support for multiple protocols, including HTTP, TCP, SSL/TLS, UDP, Reliable UDP (RUDP), and WebSocket. This versatility makes Netly an excellent choice for developing a wide range of applications, from multiplayer games and chat systems to real-time data exchanges. |
|---|---|
| Website |
Repository: github.com/alec1o/netly Documentation: netly.docs.kezero.com |
| Sponsor |
|
| Supporter |
|
Official publisher
| Nuget | Unity Asset Store |
|---|---|
| Install on Nuget | Install on Asset Store |
Notable changes
| v1.x.x | v2.x.x | v3.x.x | v4.x.x |
|---|---|---|---|
| Legacy | Legacy | Stable | Latest |
| TCP Support | TCP with Message Framing support | TCP with TLS/SSL support | HTTP client and server support |
| UDP Support | TCP and UDP performance increase | UDP with connection (timeout response) | Reliable UDP (RUDP) client and server support |
| New Message Framing protocol and performance increase | WebSocket client and server support | ||
| Upgrade to Byter 2.0 | Upgrade to Byter 4.0 | ||
| Docsify as documentation framework | Documentation improvement by Docusaurus and DocFxMarkdownGen | ||
| Syntax and internal improvement | |||
| XML comments improvement | |||
| Message framing with version, size and checksum (big-endian), events detected by content | |||
One failure contract for every protocol: OnError, then OnClose |
Technical descriptions about integrations
| List of tested platforms |
|
|---|---|
| Dependencies |
|
| Build |
# 1. clone project
$ git clone "https://github.com/alec1o/Netly" netly
# 2. build project
$ dotnet build "netly/" -c Release -o "netly/bin/"
# NOTE:
# Netly.dll require Byter.dll because is Netly dependency
# Netly.dll and Byter.dll have on build folder <netly-path>/bin/ |
| Features |
|
Code highlights
| TCP |
📄 Clientusing Netly;
TcpClient client = new TcpClient(isFraming: true);client.OnOpen(() =>
{
Console.WriteLine("connection opened");
});
client.OnClose(() =>
{
Console.WriteLine("connection closed");
});
client.OnError((exception) =>
{
// failed to open (OnClose is called after), failed to send, or the data received is invalid,
// above FramingSize or made an allocation/callback of the app throw (OnClose is called after).
Console.WriteLine("connection error");
});
client.OnData((stream) =>
{
// one sent message = one OnData. The stream starts at position 0 and is disposed
// when the callback returns, copy it if you need it later.
Console.WriteLine($"received {stream.Length} bytes");
});
client.OnEvent((name, stream) =>
{
Console.WriteLine($"received the event {name}");
});
client.OnModify((socket) =>
{
// called before try open connection, e.g. socket.NoDelay = true
});
client.OnSecure((certificate, chain, errors) =>
{
// Only if client.IsSecure is enabled, return true if the certificate is valid
return true;
});
client.OnAllocate((size) =>
{
// where each received message is written, size is the exact size of the message
// e.g. return a FileStream to keep big messages out of memory
return new MemoryStream();
});// open connection if closed
client.Open(new Host("127.0.0.1", 8080));
// close connection if opened
client.Close();
// send raw data if connected (if it is not connected, OnError is called)
client.SendData(new byte[2] { 128, 255 });
client.SendData(Encoding.UTF8.GetBytes("hello world"));
// send event if connected
client.SendEvent("name", new byte[2] { 128, 255 });
client.SendEvent("name", Encoding.UTF8.GetBytes("hello world"));
// enable TLS (must call before client.Open)
client.ToSecure(true);
// biggest message accepted (default 20 MB) and time to complete a header (default 5s)
// must be set before client.Open
client.FramingSize = 4 * 1024 * 1024;
client.HeaderTimeout = TimeSpan.FromSeconds(3);📄 Serverusing Netly;
TcpServer server = new TcpServer(isFraming: true);server.OnOpen(() =>
{
Console.WriteLine("server opened");
});
server.OnClose(() =>
{
Console.WriteLine("server closed");
});
server.OnError((exception) =>
{
Console.WriteLine("server error on open");
});
server.OnAccept((client) =>
{
client.OnModify((socket) =>
{
// modify client socket e.g. Enable NoDelay
});
client.OnOpen(() => Console.WriteLine("client connected"));
client.OnData((stream) => Console.WriteLine("client sent a raw data"));
client.OnEvent((name, stream) => Console.WriteLine("client sent an event"));
client.OnError((exception) => Console.WriteLine("client sent invalid data or a callback threw"));
client.OnClose(() => Console.WriteLine("client disconnected"));
});
server.OnModify((socket) =>
{
// called before try open connection.
});// open connection
server.Open(new Host("0.0.0.0", 1111));
// close connection
server.Close();
// enable TLS support (must called before server.Open)
server.ToSecure(pfxBytes, "pfx password", SslProtocols.Tls12, allowUnsecured: false);
// biggest message accepted from each client (default 20 MB), same value for all of them
server.FramingSize = 4 * 1024 * 1024;
// broadcast raw data for all connected client
server.BroadcastData(Encoding.UTF8.GetBytes("text buffer"));
server.BroadcastData(new byte[] { 1, 2, 3 });
// broadcast event for all connected client (or only the ones that match the condition)
server.BroadcastEvent("event name", new byte[] { 1, 2, 3 });
server.BroadcastEvent("event name", new byte[] { 1, 2, 3 }, (client) => client.IsOpened); |
|---|---|
| UDP |
📄 Clientusing Netly;
UdpClient client = new UdpClient();client.OnOpen(() =>
{
Console.WriteLine("socket opened");
});
client.OnClose(() =>
{
Console.WriteLine("socket closed");
});
client.OnError((exception) =>
{
// failed to open (OnClose is called after), failed to send, or an allocation/callback
// of the app threw (the datagram is discarded and the socket closes: OnClose is called after).
Console.WriteLine("socket error");
});
client.OnData((stream) =>
{
// one datagram = one OnData
Console.WriteLine($"received {stream.Length} bytes");
});
client.OnEvent((name, stream) =>
{
Console.WriteLine($"received the event {name}");
});
client.OnModify((socket) =>
{
// called before try open connection.
});
client.OnAllocate((size) => new MemoryStream());// open socket if closed
client.Open(new Host("127.0.0.1", 8080));
// close socket if opened
client.Close();
// biggest datagram this socket sends: the buffers of the system and, for loopback, what was seen to arrive
int max = client.MaxDatagram;
// send raw data if opened: a message that fits MaxDatagram is one datagram (any UDP program reads it),
// a bigger one (up to UdpClient.MaxDatagramSize, 65507 bytes) is sent in fragments and joined by Netly
client.SendData(new byte[2] { 128, 255 });
// send event if opened
client.SendEvent("name", new byte[2] { 128, 255 });📄 Serverusing Netly;
UdpServer server = new UdpServer();server.OnOpen(() => Console.WriteLine("server opened"));
server.OnClose(() => Console.WriteLine("server closed"));
server.OnError((exception) => Console.WriteLine("server error on open"));
server.OnAccept((client) =>
{
// a client is a peer that sent a datagram to the server
client.OnData((stream) => Console.WriteLine("peer sent a raw data"));
client.OnEvent((name, stream) => Console.WriteLine("peer sent an event"));
client.OnClose(() => Console.WriteLine("peer removed"));
});
server.OnModify((socket) =>
{
// called before try open connection.
});// open
server.Open(new Host("0.0.0.0", 1111));
// close
server.Close();
// broadcast raw data for all peers
server.BroadcastData(new byte[] { 1, 2, 3 });
// broadcast event for all peers
server.BroadcastEvent("event name", new byte[] { 1, 2, 3 }); |
| HTTP |
📄 Clientusing Netly;
HttpClient client = new HttpClient();
// add http header for request
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Token", "ImGui.h");
// add http url queries e.g: https://www.alec1o.com/?page=about&version=4
client.Queries.Add("page", "about");
client.Queries.Add("version", "4");
// request timeout (ms) default 15s (15000ms), 0 or negative value means infinite timeout.
client.Timeout = 6000; // 6s
// send the request again when it fails (attempts, delay), 0 attempts turns it off.
client.UseRetry(3, TimeSpan.FromSeconds(1));
// is opened: while is requesting
bool isFetching = client.IsOpened;// called before try connect to server, modify the System.Net.Http.HttpClient object
client.OnModify((System.Net.Http.HttpClient http) =>
{
// e.g. change the default request headers
});
// the server answered
client.OnOpen((response) =>
{
int status = response.Status;
string text = response.Body.Text;
});
// error on fetch, it can be timeout or whatever error
// but if you receive an error it means the operation is done (OnClose is called after)
client.OnError((Exception exception) =>
{
Console.WriteLine(exception);
});
// the request is over (with or without error)
client.OnClose(() =>
{
Console.WriteLine("request done");
});// used to fetch a server: method, url, body (optional)
client.Open("GET", "https://www.alec1o.com/");
client.Open("POST", "https://www.alec1o.com/user", "{ \"name\": \"alec\" }");
// used to cancel an opened request
client.Close();📄 Serverusing Netly;
HttpServer server = new HttpServer();
// return true if server is serve http context
bool isServe = server.IsOpened;server.OnOpen(() =>
{
// http server opened
});
server.OnClose(() =>
{
// http server closed
});
server.OnError((exception) =>
{
// http server open error
});
server.OnModify((httpListener) =>
{
// HttpListener instance, called before try open connection.
});
// Open http server connection
server.Open(new Uri("http://127.0.0.1:8080/"));
// Close http server connection
server.Close();// Map path
server.Map.Get("/", (req, res) =>
{
res.Send(200, "hello");
});
server.Map.Post("/user", (req, res) =>
{
res.Send(201);
});
// map using dynamic URL
server.Map.Delete("/post/{userId}/group/{groupId}", (req, res) =>
{
string userId = req.Params["userId"];
string groupId = req.Params["groupId"];
res.Send(200, $"deleted {userId} from {groupId}");
});
server.Map.WebSocket("/echo", (req, ws) =>
{
// Handle websocket connection from path (ws is a WebSocketClient)
ws.OnData((stream, delivery) => { ... });
});
/*
You can map:
* Get # get request
* Post # post request
* Delete # delete request
* Put # put request
* Patch # patch request
* Trace # trace request
* Options # options request
* Head # head request, (only head)
* All # all http method request
* WebSocket # websocket request
*//*
Note: Middlewares is executed in added order.
BUT, LOCAL MIDDLEWARE HAVE PRIORITY THAN GLOBAL MIDDLEWARE
*/
// Global Middleware (*don't have workflow path)
server.Middleware.Add((req, res, next) =>
{
var watch = Stopwatch.StartNew(); // init timer
next(); // call another middleware.
watch.Stop(); // stop timer
res.Headers.Add("Request-Timer", watch.ElapsedMilliseconds.ToString());
});
// Local middleware (have workflow path)
server.Middleware.Add("/admin", (req, res, next) =>
{
if (MyApp.CheckAdminByHeader(req.Headers))
{
res.Headers.Add("Admin-Token", MyApp.RefreshAdminHeaderToken(req));
// call next middleware
next();
}
else
{
res.Headers.Add("Content-Type", "application/json;charset=UTF-8");
res.Send(404, "{ 'error': 'invalid request.' }");
// skip other middlewares: don't call next()
}
});// Register parse middleware
server.Middleware.Add((request, response, next) =>
{
if (request.Enctype == HttpEnctype.Json)
{
request.Body.RegisterParser(true, (Type type) =>
{
// e.g. using dotnet >= 6 @System.Text.Json
return JsonSerializer.Deserialize(request.Body.Text, type);
});
}
...
next();
});
// Usage of body parser.
server.Map.Post("/register", (request, response) =>
{
var data = request.Body.Parse<MyLoginInput>();
...
}); |
| RUDP |
📄 Clientusing Netly;
RudpClient client = new RudpClient();client.OnOpen(() =>
{
Console.WriteLine("connection opened");
});
client.OnClose(() =>
{
Console.WriteLine("connection closed");
});
client.OnError((exception) =>
{
// failed to open (OnClose is called after), failed to send, or the data received is invalid,
// above FramingSize or made an allocation/callback of the app throw (OnClose is called after).
Console.WriteLine("connection error");
});
client.OnData((stream, delivery) =>
{
// delivery: how the message arrived (Reliable, Sequenced or Unreliable)
Console.WriteLine($"received {stream.Length} bytes by {delivery}");
});
client.OnEvent((name, stream, delivery) =>
{
Console.WriteLine($"received the event {name} by {delivery}");
});
client.OnModify((socket) =>
{
// called before try open connection.
});
client.OnAllocate((size) => new MemoryStream());// open connection if closed
client.Open(new Host("127.0.0.1", 8080));
// close connection if opened
client.Close();
// send raw data if connected (default is RudpDelivery.Reliable)
client.SendData(new byte[2] { 128, 255 });
client.SendData(new byte[2] { 128, 255 }, RudpDelivery.Unreliable);
client.SendData(new byte[2] { 128, 255 }, RudpDelivery.Sequenced);
// send event if connected
client.SendEvent("name", new byte[2] { 128, 255 }, RudpDelivery.Reliable);
// biggest message accepted (default 20 MB), biggest amount of bytes waiting to be sent (default 64 MB),
// time without any packet from the other side before the connection closes (default 5s)
// and time to wait the handshake (default 5s), must be set before client.Open
client.FramingSize = 4 * 1024 * 1024;
client.MaxPendingSize = 16 * 1024 * 1024;
client.NoResponseTimeout = 8000;
client.HandshakeTimeout = 3000;📄 Serverusing Netly;
RudpServer server = new RudpServer();server.OnOpen(() => Console.WriteLine("server opened"));
server.OnClose(() => Console.WriteLine("server closed"));
server.OnError((exception) => Console.WriteLine("server error on open"));
server.OnAccept((client) =>
{
client.OnOpen(() => Console.WriteLine("client connected"));
client.OnData((stream, delivery) => Console.WriteLine("client sent a raw data"));
client.OnEvent((name, stream, delivery) => Console.WriteLine("client sent an event"));
client.OnClose(() => Console.WriteLine("client disconnected"));
});
server.OnModify((socket) =>
{
// called before try open connection.
});// open
server.Open(new Host("0.0.0.0", 1111));
// close
server.Close();
// broadcast raw data for all connected client
server.BroadcastData(new byte[] { 1, 2, 3 });
server.BroadcastData(new byte[] { 1, 2, 3 }, RudpDelivery.Unreliable);
// broadcast event for all connected client (or only the ones that match the condition)
server.BroadcastEvent("event name", new byte[] { 1, 2, 3 }, RudpDelivery.Reliable); |
| WebSocket |
📄 Clientusing Netly;
WebSocketClient client = new WebSocketClient();
// headers sent in the handshake (must be set before client.Open)
client.Headers.Add("Token", "my-token");client.OnOpen(() =>
{
Console.WriteLine("connection opened");
});
client.OnClose(() =>
{
Console.WriteLine("connection closed");
});
client.OnClose((status) =>
{
Console.WriteLine($"connection closed with {status}");
});
client.OnError((exception) =>
{
// failed to open (OnClose is called after), or the message is above FramingSize or made
// an allocation/callback of the app throw (the connection closes: OnClose is called after).
Console.WriteLine("connection error");
});
client.OnData((stream, delivery) =>
{
// delivery: WebSocketDelivery.Binary or WebSocketDelivery.Text
Console.WriteLine($"received {stream.Length} bytes");
});
client.OnEvent((name, stream, delivery) =>
{
Console.WriteLine($"received the event {name}");
});
client.OnModify((clientWebSocket) =>
{
// called before try open connection.
});
// A WebSocket does not tell the size of a message before its end, so there is no OnAllocate:
// OnDynamicAllocation is called with 0 to start the message and again with the current size
// (8 KB, 16 KB, 32 KB...) when it grows. Return a bigger stream (the content is copied to it and the
// old one is disposed) or null to keep the current one.
client.OnDynamicAllocation((size) =>
{
return size <= 1024 * 1024 ? new MemoryStream() : null;
});// open connection if closed
client.Open(new Uri("ws://127.0.0.1:8080/chat"));
// close connection if opened
client.Close();
client.Close(WebSocketCloseStatus.NormalClosure);
// send raw data if connected (Binary is the default)
client.SendData(new byte[2] { 128, 255 });
client.SendData(Encoding.UTF8.GetBytes("hello world"), WebSocketDelivery.Text);
// send event if connected
client.SendEvent("name", Encoding.UTF8.GetBytes("hello world"), WebSocketDelivery.Text);
// biggest message accepted (default 20 MB), must be set before client.Open
client.FramingSize = 4 * 1024 * 1024;📄 Serverusing Netly;
WebSocketServer server = new WebSocketServer();server.OnOpen(() => Console.WriteLine("server opened"));
server.OnClose(() => Console.WriteLine("server closed"));
server.OnError((exception) => Console.WriteLine("server error on open"));
server.OnAccept((client) =>
{
client.OnOpen(() => Console.WriteLine("client connected"));
client.OnData((stream, delivery) => Console.WriteLine("client sent a raw data"));
client.OnEvent((name, stream, delivery) => Console.WriteLine("client sent an event"));
client.OnClose(() => Console.WriteLine("client disconnected"));
});
server.OnModify((httpListener) =>
{
// HttpListener instance, called before try open connection.
});
// where each message of the clients is written, same rules of the client
server.OnDynamicAllocation((size) => new MemoryStream());// open (the path is where the clients connect)
server.Open(new Uri("ws://127.0.0.1:8080/chat"));
// close
server.Close();
// biggest message accepted from each client (default 20 MB), must be set before server.Open
server.FramingSize = 4 * 1024 * 1024;
// broadcast raw data for all connected websocket
// text message
server.BroadcastData(Encoding.UTF8.GetBytes("my message"), WebSocketDelivery.Text);
// binary message
server.BroadcastData(new byte[] { 1, 2, 3 }, WebSocketDelivery.Binary);
// broadcast event for all connected websocket
server.BroadcastEvent("event name", Encoding.UTF8.GetBytes("my message"), WebSocketDelivery.Text);
server.BroadcastEvent("event name", new byte[] { 1, 2, 3 }, WebSocketDelivery.Binary); |
| Byter |
For more information and details see Byter's official information
📄 Primitiveusing Byter;
Primitive can serialize/deserialize complex data, e.g. (T[], List, Class, Struct, Enum).
📄 Extensionusing Byter;
|
What goes on the wire and what happens when something fails. Every multi-byte value is big-endian (network byte order).
| Framing |
TCP is a stream of bytes, so each message starts with a header that tells where it ends. RUDP uses the same header at the start of every message (reliable, sequenced and unreliable). UDP is one datagram per message and WebSocket delimits its own messages, so they don't need it.
The size is checked against |
||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Event |
An event is detected by its content, so any peer can send one by writing these bytes: no extra field of the transport is needed. When the prefix, the checksum, the exact sizes or the name (UTF-8) don't match, the message is delivered as data (OnData).
|
||||||||||||||||||||||||
| Failures |
The same contract for TCP, UDP, RUDP and WebSocket. There is no automatic reconnection: to connect again, call Open inside OnClose.
The message that caused the failure is always discarded. An exception thrown inside |
||||||||||||||||||||||||
| UDP |
One message is one datagram, as any UDP program expects. Some systems drop big datagrams without any error (macOS sends up to its send buffer, and some machines lose the ones above ~4 KB until the other side answers), so Netly measures what a new socket delivers to loopback (once) and uses the send buffer as limit: MaxDatagram. A message above it is split in fragments and joined by the receiver. The fragment is detected by its content, like the event, so any other datagram is delivered as it is.
A message that does not complete in 2 seconds is dropped, up to 16 messages wait at the same time for each peer, and a message is never bigger than 65507 bytes.
|
||||||||||||||||||||||||
| Allocation |
The stream where a received message is written is chosen by the app.
An exception or a failed copy discards the message and closes the connection ( |
||||||||||||||||||||||||
| RUDP |
Reliable UDP keeps the same connection through short network drops (retransmission with growing timeout and keep-alive) and closes it when nothing arrives for NoResponseTimeout (default 5 seconds). The wire format is big-endian, version 3 of the handshake: peers of other versions are refused.
|
Integration and interaction example codes
| Standard |
📄 Consoleusing System;
using System.Text;
using Netly;
public class Program
{
private static void Main(string[] args)
{
UdpClient client = new UdpClient();
Host host = new Host("1.1.1.1", 1111);
client.OnOpen(() =>
{
Console.WriteLine("opened");
});
client.OnClose(() =>
{
Console.WriteLine("closed, open it again");
client.Open(host);
});
client.OnError((exception) =>
{
Console.WriteLine(exception.Message);
});
client.Open(host);
while (true)
{
Console.WriteLine("Message: ");
string message = Console.ReadLine();
if (client.IsOpened)
client.SendData(Encoding.UTF8.GetBytes(message ?? "No message."));
}
}
} |
|---|---|
| Flax Engine |
📄 Scriptusing System.Text;
using FlaxEngine;
using Netly;
public class Example : Script
{
public string message;
internal UdpClient client;
private readonly Host host = new Host("1.1.1.1", 1111);
public override void OnAwake()
{
client = new UdpClient();
client.OnOpen(() =>
{
Debug.Log("opened");
});
client.OnClose(() =>
{
Debug.Log("closed");
});
client.OnError((exception) =>
{
Debug.Log(exception.Message);
});
}
public override void OnStart()
{
client.Open(host);
}
public override void OnUpdate()
{
if (client.IsOpened && Input.GetKeyDown(KeyboardKeys.Spacebar))
{
client.SendData(Encoding.UTF8.GetBytes(message ?? "No message."));
}
}
} |
| Unity Engine |
📄 MonoBehaviourusing System.Text;
using UnityEngine;
using Netly;
public class Example : MonoBehaviour
{
public string message;
internal UdpClient client;
private readonly Host host = new Host("1.1.1.1", 1111);
private void Awake()
{
client = new UdpClient();
client.OnOpen(() =>
{
Debug.Log("opened");
});
client.OnClose(() =>
{
Debug.Log("closed");
});
client.OnError((exception) =>
{
Debug.Log(exception.Message);
});
}
private void Start()
{
client.Open(host);
}
private void Update()
{
if (client.IsOpened && Input.GetKeyDown(KeyCode.Space))
{
client.SendData(Encoding.UTF8.GetBytes(message ?? "No message."));
}
}
} |
| WARNING: |
Initialize event handlers once, not in loops. Set up handlers with the client.On<Event>(...) and server.On<Event>(...) methods (OnOpen, OnClose, OnError, OnData, OnEvent...) in initialization methods like Awake() or Start(). Every call adds a new handler, so calling them repeatedly in update loops makes the same code run many times.
Handle protocol actions wisely. Use Open(), SendData(), SendEvent() and Close() with careful management. Ensure you only open a connection when it's not already open and send data only when the connection is confirmed as active (IsOpened). Avoid calling these methods in tight loops. To connect again after a failure, call Open() inside OnClose: there is no automatic reconnection.
// OK 100% Recommended
private void Start()
{
var client = ...;
client.OnOpen(() => ...); // e.g generic handler
client.OnOpen(() => ...); // e.g only to send "Hi"
client.OnEvent((name, stream) => ...); // e.g generic event handler
client.OnEvent((name, stream) => ...); // e.g only to handle A event
client.OnEvent((name, stream) => ...); // e.g only to handle B event
client.Open(...);
}public void Update()
{
client.Open(...); // [OK? - May Not In Loop?]
client.SendData(...); // [OK? - May Not In Loop?]
client.SendEvent(...); // [OK? - May Not In Loop?]
client.Close(...); // [OK? - May Not In Loop?]
ws.OnOpen(() => ...); // [BAD - Never In Loop]
ws.OnClose(() => ... ); // [BAD - Never In Loop]
ws.OnData((stream, delivery) => ...);// [BAD - Never In Loop]
ws.OnError((exception) => ... ); // [BAD - Never In Loop]
ws.OnEvent((name, stream, delivery) => ... ); // [BAD - Never In Loop]
} |