Simple and practical Socket framework DotNettySocket

Keywords: C# encoding socket Javascript github

Catalog

brief introduction

DotNettySocket is a.NET cross-platform Socket framework that supports.NET 4.5+ and.NET Standard 2.0+. It also supports TcpSocket, WebSocket and UdpSocket. Based on Microsoft's strong DotNetty framework, DotNetty Socket strives to provide a simple, efficient and elegant way of operating Socket communication.

Installation method: Nuget can install DotNettySocket

Project Address: https://github.com/Coldairarrow/DotNettySocket

Generate Background

Tcp and Udp communication were needed when I first came into contact with the Internet of Things two years ago. For convenience, the original Socket was simply encapsulated, basically meeting the requirements, and the framework was open source.However, due to the limited energy and strength, the original framework has not been further optimized.A strong DotNetty framework was discovered. DotNetty is an open source, Java Netty-based portal of the Microsoft Azure team. It has excellent performance, a strong maintenance team and is used by many powerful.NET frameworks.DotNetty is powerful, but it's not simple enough (maybe personal) to use it. Recent projects just need WebSocket s, so people take the time to wrap up a simple, efficient and elegant framework based on DotNetty.

Usage

TcpSocket

Tcp is connection-oriented, so the management of connections on the server side is critical. The framework supports the handling of events, setting connection names (identities) for connections, finding specific connections through connection names, receiving and receiving data for connections, subcontracting, and gluing.

  • Server
using Coldairarrow.DotNettySocket;
using System;
using System.Text;
using System.Threading.Tasks;

namespace TcpSocket.Server
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var theServer = await SocketBuilderFactory.GetTcpSocketServerBuilder(6001)
                .SetLengthFieldEncoder(2)
                .SetLengthFieldDecoder(ushort.MaxValue, 0, 2, 0, 2)
                .OnConnectionClose((server, connection) =>
                {
                    Console.WriteLine($"Connection closed,Connection Name[{connection.ConnectionName}],Current number of connections:{server.GetConnectionCount()}");
                })
                .OnException(ex =>
                {
                    Console.WriteLine($"Server side exception:{ex.Message}");
                })
                .OnNewConnection((server, connection) =>
                {
                    connection.ConnectionName = $"Name{connection.ConnectionId}";
                    Console.WriteLine($"New Connection:{connection.ConnectionName},Current number of connections:{server.GetConnectionCount()}");
                })
                .OnRecieve((server, connection, bytes) =>
                {
                    Console.WriteLine($"Server:data{Encoding.UTF8.GetString(bytes)}");
                    connection.Send(bytes);
                })
                .OnSend((server, connection, bytes) =>
                {
                    Console.WriteLine($"To Connection Name[{connection.ConnectionName}]send data:{Encoding.UTF8.GetString(bytes)}");
                })
                .OnServerStarted(server =>
                {
                    Console.WriteLine($"Service Start");
                }).BuildAsync();

            Console.ReadLine();
        }
    }
}
  • Client
using Coldairarrow.DotNettySocket;
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace UdpSocket.Client
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var theClient = await SocketBuilderFactory.GetUdpSocketBuilder()
                .OnClose(server =>
                {
                    Console.WriteLine($"Client shutdown");
                })
                .OnException(ex =>
                {
                    Console.WriteLine($"Client Exception:{ex.Message}");
                })
                .OnRecieve((server, point, bytes) =>
                {
                    Console.WriteLine($"Client:Received from[{point.ToString()}]data:{Encoding.UTF8.GetString(bytes)}");
                })
                .OnSend((server, point, bytes) =>
                {
                    Console.WriteLine($"Client sends data:target[{point.ToString()}]data:{Encoding.UTF8.GetString(bytes)}");
                })
                .OnStarted(server =>
                {
                    Console.WriteLine($"Client Start");
                }).BuildAsync();

            while (true)
            {
                await theClient.Send(Guid.NewGuid().ToString(), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6003));
                await Task.Delay(1000);
            }
        }
    }
}

WebSocket

The WebSocket and TcpSocket interfaces are basically identical, except that the TcpSocket supports byte delivery and needs to handle the subpackage glue on its own.WebSocket directly sends and receives string (UTF-8) encoding without regard to subpackage glue.The framework does not currently support WSS, and the recommended solution is to use Nginx forwarding (as soon as relevant information is available)

  • Server
using Coldairarrow.DotNettySocket;
using System;
using System.Threading.Tasks;

namespace WebSocket.Server
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var theServer = await SocketBuilderFactory.GetWebSocketServerBuilder(6002)
                .OnConnectionClose((server, connection) =>
                {
                    Console.WriteLine($"Connection closed,Connection Name[{connection.ConnectionName}],Current number of connections:{server.GetConnectionCount()}");
                })
                .OnException(ex =>
                {
                    Console.WriteLine($"Server side exception:{ex.Message}");
                })
                .OnNewConnection((server, connection) =>
                {
                    connection.ConnectionName = $"Name{connection.ConnectionId}";
                    Console.WriteLine($"New Connection:{connection.ConnectionName},Current number of connections:{server.GetConnectionCount()}");
                })
                .OnRecieve((server, connection, msg) =>
                {
                    Console.WriteLine($"Server:data{msg}");
                    connection.Send(msg);
                })
                .OnSend((server, connection, msg) =>
                {
                    Console.WriteLine($"To Connection Name[{connection.ConnectionName}]send data:{msg}");
                })
                .OnServerStarted(server =>
                {
                    Console.WriteLine($"Service Start");
                }).BuildAsync();

            Console.ReadLine();
        }
    }
}
  • Console Client
using Coldairarrow.DotNettySocket;
using System;
using System.Threading.Tasks;

namespace WebSocket.ConsoleClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var theClient = await SocketBuilderFactory.GetWebSocketClientBuilder("127.0.0.1", 6002)
                .OnClientStarted(client =>
                {
                    Console.WriteLine($"Client Start");
                })
                .OnClientClose(client =>
                {
                    Console.WriteLine($"Client shutdown");
                })
                .OnException(ex =>
                {
                    Console.WriteLine($"abnormal:{ex.Message}");
                })
                .OnRecieve((client, msg) =>
                {
                    Console.WriteLine($"Client:Received data:{msg}");
                })
                .OnSend((client, msg) =>
                {
                    Console.WriteLine($"Client:send data:{msg}");
                })
                .BuildAsync();

            while (true)
            {
                await theClient.Send(Guid.NewGuid().ToString());

                await Task.Delay(1000);
            }
        }
    }
}
  • Web Client
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>Rookie Bird Tutorial(runoob.com)</title>

    <script type="text/javascript">
        function WebSocketTest() {
            if ("WebSocket" in window) {
                var ws = new WebSocket("ws://127.0.0.1:6002");

                ws.onopen = function () {
                    console.log('Connect to server');
                    setInterval(function () {
                        ws.send("111111");
                    }, 1000);
                };

                ws.onmessage = function (evt) {
                    var received_msg = evt.data;
                    console.log('Received' + received_msg);
                };

                ws.onclose = function () {
                    console.log("Connection closed...");
                };
            }

            else {
                alert("Your browser does not support it WebSocket!");
            }
        }
    </script>

</head>
<body>
    <div id="sse">
        <a href="javascript:WebSocketTest()">Function WebSocket</a>
    </div>
</body>
</html>

UdpSocket

Udp is inherently a combination of sending and receiving. The following are divided into service and client for ease of understanding

  • Server
using Coldairarrow.DotNettySocket;
using System;
using System.Text;
using System.Threading.Tasks;

namespace UdpSocket.Server
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var theServer = await SocketBuilderFactory.GetUdpSocketBuilder(6003)
                .OnClose(server =>
                {
                    Console.WriteLine($"Server shutdown");
                })
                .OnException(ex =>
                {
                    Console.WriteLine($"Server side exception:{ex.Message}");
                })
                .OnRecieve((server, point, bytes) =>
                {
                    Console.WriteLine($"Server:Received from[{point.ToString()}]data:{Encoding.UTF8.GetString(bytes)}");
                    server.Send(bytes, point);
                })
                .OnSend((server, point, bytes) =>
                {
                    Console.WriteLine($"Server sends data:target[{point.ToString()}]data:{Encoding.UTF8.GetString(bytes)}");
                })
                .OnStarted(server =>
                {
                    Console.WriteLine($"Server Start");
                }).BuildAsync();

            Console.ReadLine();
        }
    }
}
  • Client
using Coldairarrow.DotNettySocket;
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace UdpSocket.Client
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var theClient = await SocketBuilderFactory.GetUdpSocketBuilder()
                .OnClose(server =>
                {
                    Console.WriteLine($"Client shutdown");
                })
                .OnException(ex =>
                {
                    Console.WriteLine($"Client Exception:{ex.Message}");
                })
                .OnRecieve((server, point, bytes) =>
                {
                    Console.WriteLine($"Client:Received from[{point.ToString()}]data:{Encoding.UTF8.GetString(bytes)}");
                })
                .OnSend((server, point, bytes) =>
                {
                    Console.WriteLine($"Client sends data:target[{point.ToString()}]data:{Encoding.UTF8.GetString(bytes)}");
                })
                .OnStarted(server =>
                {
                    Console.WriteLine($"Client Start");
                }).BuildAsync();

            while (true)
            {
                await theClient.Send(Guid.NewGuid().ToString(), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6003));
                await Task.Delay(1000);
            }
        }
    }
}

Ending

All the above examples are available in the source code. If you think they are good, Please add some stars. I hope they can help you.

Feedback or group communication if you have any questions

QQ Group 1: (full)

QQ Group 2:579202910

Posted by perfume on Sun, 11 Aug 2019 17:51:40 -0700