Skip to content
alec1oPublic

About

Netly: Cross-Platform, Multi-Protocol C# Socket Library – Fast, Easy, and Versatile.⚡

Topics

Resources

Code of conduct

Security policy

Stars

110 stars

Watchers

5 watching

Forks

Repository files navigation

Active development occurs on the 'dev' branch. For the stable release, refer to the 'main' branch.

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!
✨ Every like/star is a powerful boost that drives us forward.
💙 Thank you for your incredible support!


powered by ALEC1O

Project

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
Why Contribute to Netly?
  • Transform Network Communication:
    Join us in revolutionizing how software communicates. Your contributions will help build a library that sets new standards for efficiency and reliability.
  • Advance Your Career:
    Engage with innovative projects, solve complex problems, and collaborate with experts. Your involvement will sharpen your skills and expand your professional network.
  • Share Your Ideas:
    Whether you're a seasoned developer or just starting out, your ideas are valuable. Contribute thoughts and suggestions to shape the future of Netly and drive innovation.


Installing

Official publisher

Nuget Unity Asset Store
Install on Nuget Install on Asset Store

Versions

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

Integrations

Technical descriptions about integrations

List of tested platforms
  • .NET (SDK)
  • Mono (SDK)
  • Unity (Engine)
  • Operating system (OS)
    • Android
    • iOS
    • Windows
    • Linux
    • macOS

      Notice: This library might run on all devices. If it doesn't work on any device, it should be considered a bug and reported.

Dependencies
byter logo Byter
Build
Build dependencies
Build step-by-step
# 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

Below are some missing features that are planned to be added in later versions.

  • N/A


Examples

Code highlights

TCP
📄 Client
using 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);
📄 Server
using 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
📄 Client
using 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 });
📄 Server
using 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
📄 Client
using 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();
📄 Server
using 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
// 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
*/
Middleware
/*
    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()
    }
});
Body Parser
// 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
📄 Client
using 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;
📄 Server
using 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
📄 Client
using 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;
📄 Server
using 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

Byter documentation: alec1o/Byter

📄 Primitive
using Byter;
  • Serialize (have +20 types of data supported, e.g. enum, bool, array, list, class, struct,... see official docs

    Primitive primitive = new();
    
    // add element
    
    primitive.Add.ULong(1024);                 // e.g. Id
    primitive.Add.DateTime(DateTime.UtcNow);   // e.g. Sent Time
    primitive.Add.Struct(new Student() {...}); // e.g Student
    primitive.Add.Class(new Employee() {...}); // e.g Employee
    ...
    
    // get buffer
    byte[] buffer = primitive.GetBytes();
  • Deserialize

    // WARNING: Need primitive buffer to deserialize
    Primitive primitive = new(...buffer);
    
    ulong id = primitive.Get.ULong();
    DateTime sentTime = primitive.Get.DateTime();
    Student student = primitive.Get.Struct<Student>();
    Employee employee = primitive.Get.Class<Employee>();
    
    /*
        * NOTE: Primitive don't make exception when diserialize error,
        * don't need try/catch block
    */
    if (primitive.IsValid is false)
    {
        // discart this. +1/all failed on deserialize
        return;
    }
    
    // deserialized sucessful
  • *Dynamic Read Technical

    Primitive primitive = new(...buffer);
    
    var topic = primitive.Get.Enum<Topic>();
    
    if(!primitive.IsValid) return; // discart this, topic not found.
    
    switch(topic)
    {
        case Topic.Student:
        {
            // read student info e.g.
            var student = primitive.Get.Struct<Student>();
            ...
            return;
        }
    
        case Topic.Employee:
        {
            // read employee info e.g.
            var employee = primitive.Get.Class<Employee>();
            ...
            return;
        }
    
        default:
        {
            // discart this, topic not found.
            ...
            return;
        }
    }

Warning

Primitive can serialize/deserialize complex data, e.g. (T[], List, Class, Struct, Enum).
But when you want to deserialize your (Class, Structure, List<Class/Struct>, Class/Struct[]), It must have:

  • (generic and public constructor: is a public constructor with no arguments, e.g. which allows:

    Human human = new Human();
  • And the class/struct property must have public access and { get; set; } or not private for example. (In byter programming, ONLY PROPERTIES THAT CAN BE READ AND WRITTEN WILL BE SERIALIZED AND DESERIALIZED)

    // valid
    public string Name;
    public string Name { get; set; }
    internal string Name; // !!! if visible from Byter
    internal string Name { get; set; }; // !!! if visible from Byter
    
    // invalid
    private string Name;
    private string Name { get; set; }
    internal string Name; // !!! if unvisible from Byter
    internal string Name { get; set; }; // !!! if unvisible from Byter

Example
  • Sample of complex data

    public class Human
    {
        public BigInteger IdNumber { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBirth { get; set; }
        public GenderType Gender { get; set; } // enum
        public byte[] Picture { get; set; }
    
    }
    
    public class Employee
    {
        public Human Human { get; set; }
        public string Position { get; set; }
        public DateTime HireDate { get; set; }
        public int YearsOfService { get; set; }
    }
    
    public struct Student
    {
        public string Major { get; set; }
        public DateTime EnrollmentDate { get; set; }
        public List<Book> Books { get; set; }
    
    }
    
    public class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public string ISBN { get; set; }
        public int PublicationYear { get; set; }
        public string Publisher { get; set; }
        public decimal Price { get; set; }
    }
📄 Extension
using Byter;
  • Global Default Encoding (source code spec)

    // update global defaut encoding. Default is UTF8
    StringExtension.Default = Encoding.Unicode; // Unicode is UTF16
  • Convert string to byte[]

    // using global encoding (*UTF8)
    byte[] username  = "@alec1o".GetBytes();
    
    // using UNICODE (*UTF16) encoding
    byte[] message = "Hello 👋 World 🌎".GetBytes(Encoding.Unicode);
    
    // using UTF32 encoding
    string secreatWord = "I'm not human, I'm  a concept.";
    byte[] secreat = secreatWord.GetBytes(Encoding.UTF32);
  • Convert byte[] to string

    // using global encoding (*UTF8)
    string username  = new byte[] { ... }.GetString();
    
    // using UNICODE (*UTF16) encoding
    string message = new byte[] { ... }.GetString(Encoding.Unicode);
    
    // using UTF32 encoding
    byte[] secreat = new byte[] { ... };
    string secreatWord = secreat.GetString(Encoding.UTF32);
  • Capitalize string

    string name = "alECio furanZE".ToCapitalize();
    # Alecio Furanze
    
    string title = "i'M noT humAn";
    title = title.ToCapitalize();
    # I'm Not Human
  • UpperCase string

    string name = "alECio furanZE".ToUpperCase();
    # ALECIO FURANZE
    
    string title = "i'M noT humAn";
    title = title.ToUpperCase();
    # I'M NOT HUMAN
  • LowerCase string

    string name = "ALEciO FUraNZE".ToLowerCase();
    # alecio furanze
    
    string title = "i'M Not huMAN";
    title = title.ToLowerCase();
    # i'm not human


Protocol

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.

Field Size Description
Version 1 B Header version, 1
Length 8 B Size of the payload (ulong), 1 to FramingSize
Checksum 1 B CRC-8 (polynomial 0x07) of Version + Length
Payload Length Data or event

The size is checked against FramingSize (default 20 MB) before any memory is allocated, and the checksum tells a header from data out of alignment. A peer that starts a header and stops (HeaderTimeout, default 5 seconds on TCP) is disconnected.

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).

Field Size Description
Prefix 2 B 19 36, read each byte in decimal: 1936, the year of the Turing Machine
NameSize 2 B Size of the name in bytes (ushort), 1 to 65535
BodySize 8 B Size of the body (ulong)
Checksum 1 B CRC-8 of Prefix + NameSize + BodySize
Name NameSize Event name, UTF-8
Body BodySize Event content

Failures The same contract for TCP, UDP, RUDP and WebSocket. There is no automatic reconnection: to connect again, call Open inside OnClose.

What happened OnError OnClose
The connection fails to open yes yes, after
Invalid header, message above FramingSize, header not completed yes yes, after
OnAllocate (or a write to its stream) throws yes yes, after
An exception of the app in OnData or OnEvent yes yes, after
Send without an open connection yes no
The send queue of RUDP is full (MaxPendingSize, default 64 MB) yes yes, after
The other side closes or the network drops no yes

The message that caused the failure is always discarded. An exception thrown inside OnOpen, OnClose or OnError is only logged. UDP has no connection: a failure closes the socket (or removes the peer, on a server).

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.

Field Size Description
Prefix 2 B 36 19
Id 2 B Message id (ushort)
Index 1 B Position of the fragment, from 0
Count 1 B How many fragments the message has, at least 2
Checksum 1 B CRC-8 of the fields before it
Payload rest A part of the message

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.

Callback Protocols How it is called
OnAllocate(size) TCP, UDP, RUDP Once for each message, with its exact size
OnDynamicAllocation(size) WebSocket First with 0, then with the current size when the message grows (8 KB, 16 KB, 32 KB...). Return a bigger stream (the library copies the content and disposes the old one) or null to keep the current one

An exception or a failed copy discards the message and closes the connection (OnError, then OnClose).

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.


Usage

Integration and interaction example codes

Standard
📄 Console
using 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
📄 Script
using 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
📄 MonoBehaviour
using 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]
}

About

Netly: Cross-Platform, Multi-Protocol C# Socket Library – Fast, Easy, and Versatile.⚡

Topics

Resources

Code of conduct

Security policy

Stars

110 stars

Watchers

5 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages