{"id":19991025,"url":"https://github.com/Coldairarrow/DotNettySocket","last_synced_at":"2025-05-04T10:30:58.942Z","repository":{"id":97176352,"uuid":"201707865","full_name":"Coldairarrow/DotNettySocket","owner":"Coldairarrow","description":"An Easy Socket(TcpSocket,WebSocket,UdpSocket) Framework Based On DotNetty","archived":false,"fork":false,"pushed_at":"2019-09-01T07:44:37.000Z","size":77,"stargazers_count":274,"open_issues_count":6,"forks_count":73,"subscribers_count":10,"default_branch":"master","last_synced_at":"2024-11-13T04:53:00.408Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Coldairarrow.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-08-11T02:39:29.000Z","updated_at":"2024-11-09T03:06:32.000Z","dependencies_parsed_at":null,"dependency_job_id":"7c7b0443-540f-43b0-8ad9-0c5d91636f4c","html_url":"https://github.com/Coldairarrow/DotNettySocket","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Coldairarrow%2FDotNettySocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Coldairarrow%2FDotNettySocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Coldairarrow%2FDotNettySocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Coldairarrow%2FDotNettySocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Coldairarrow","download_url":"https://codeload.github.com/Coldairarrow/DotNettySocket/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252320072,"owners_count":21729061,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-13T04:51:35.273Z","updated_at":"2025-05-04T10:30:57.545Z","avatar_url":"https://github.com/Coldairarrow.png","language":"C#","funding_links":[],"categories":["C\\#"],"sub_categories":[],"readme":"# 目录\n- [简介](#简介)\n- [产生背景](#产生背景)\n- [使用方式](#使用方式)\n\t- [TcpSocket](#TcpSocket)\n\t- [WebSocket](#WebSocket)\n\t- [UdpSocket](#UdpSocket)\n- [结尾](#结尾)\n\n# 简介\nDotNettySocket是一个.NET跨平台Socket框架（支持.NET4.5+及.NET Standard2.0+），同时支持TcpSocket、WebSocket和UdpSocket，其基于微软强大的DotNetty框架，力求为Socket通讯提供**简单**、**高效**、**优雅**的操作方式。\n\n安装方式：Nuget安装**DotNettySocket**即可\n\n项目地址：https://github.com/Coldairarrow/DotNettySocket\n\n# 产生背景\n两年前最开始接触物联网的时候，需要用到Tcp及Udp通讯，为了方便使用，将原始的Socket进行了简单的封装，基本满足了需求，并将框架开源。但是由于精力及实力有限，没有进一步优化原框架。后来发现了强大的DotNetty框架，DotNetty是微软Azure团队开源基于Java Netty框架的移植版，其性能优异、维护团队强大，许多.NET强大的框架都使用它。DotNetty功能强大，但是用起来还是不够简洁（或许是个人感觉），刚好最近项目需要用到WebSocket，因此鄙人抽时间基于DotNetty进行简单封装了下，撸出一个力求**简单、高效、优雅**的Socket框架。\n\n# 使用方式\n\n## TcpSocket\nTcp是面向连接的，所以服务端对连接的管理就至关重要，框架支持各种事件的处理、给连接设置连接名（身份标识）、通过连接名找到特定连接、连接收发数据、分包、粘包处理。\n- 服务端\n``` c#\nusing Coldairarrow.DotNettySocket;\nusing System;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace TcpSocket.Server\n{\n    class Program\n    {\n        static async Task Main(string[] args)\n        {\n            var theServer = await SocketBuilderFactory.GetTcpSocketServerBuilder(6001)\n                .SetLengthFieldEncoder(2)\n                .SetLengthFieldDecoder(ushort.MaxValue, 0, 2, 0, 2)\n                .OnConnectionClose((server, connection) =\u003e\n                {\n                    Console.WriteLine($\"连接关闭,连接名[{connection.ConnectionName}],当前连接数:{server.GetConnectionCount()}\");\n                })\n                .OnException(ex =\u003e\n                {\n                    Console.WriteLine($\"服务端异常:{ex.Message}\");\n                })\n                .OnNewConnection((server, connection) =\u003e\n                {\n                    connection.ConnectionName = $\"名字{connection.ConnectionId}\";\n                    Console.WriteLine($\"新的连接:{connection.ConnectionName},当前连接数:{server.GetConnectionCount()}\");\n                })\n                .OnRecieve((server, connection, bytes) =\u003e\n                {\n                    Console.WriteLine($\"服务端:数据{Encoding.UTF8.GetString(bytes)}\");\n                    connection.Send(bytes);\n                })\n                .OnSend((server, connection, bytes) =\u003e\n                {\n                    Console.WriteLine($\"向连接名[{connection.ConnectionName}]发送数据:{Encoding.UTF8.GetString(bytes)}\");\n                })\n                .OnServerStarted(server =\u003e\n                {\n                    Console.WriteLine($\"服务启动\");\n                }).BuildAsync();\n\n            Console.ReadLine();\n        }\n    }\n}\n```\n- 客户端\n``` c#\nusing Coldairarrow.DotNettySocket;\nusing System;\nusing System.Net;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace UdpSocket.Client\n{\n    class Program\n    {\n        static async Task Main(string[] args)\n        {\n            var theClient = await SocketBuilderFactory.GetUdpSocketBuilder()\n                .OnClose(server =\u003e\n                {\n                    Console.WriteLine($\"客户端关闭\");\n                })\n                .OnException(ex =\u003e\n                {\n                    Console.WriteLine($\"客户端异常:{ex.Message}\");\n                })\n                .OnRecieve((server, point, bytes) =\u003e\n                {\n                    Console.WriteLine($\"客户端:收到来自[{point.ToString()}]数据:{Encoding.UTF8.GetString(bytes)}\");\n                })\n                .OnSend((server, point, bytes) =\u003e\n                {\n                    Console.WriteLine($\"客户端发送数据:目标[{point.ToString()}]数据:{Encoding.UTF8.GetString(bytes)}\");\n                })\n                .OnStarted(server =\u003e\n                {\n                    Console.WriteLine($\"客户端启动\");\n                }).BuildAsync();\n\n            while (true)\n            {\n                await theClient.Send(Guid.NewGuid().ToString(), new IPEndPoint(IPAddress.Parse(\"127.0.0.1\"), 6003));\n                await Task.Delay(1000);\n            }\n        }\n    }\n}\n\n```\n## WebSocket\nWebSocket与TcpSocket接口基本保持一致，仅有的区别就是TcpSocket支持字节的收发并且需要自行处理分包粘包。而WebSocket直接收发字符串（UTF-8）编码，并且无需考虑分包粘包。框架目前没有支持WSS，建议解决方案是使用Nginx转发即可（相关资料一搜便有）\n- 服务端\n``` c#\nusing Coldairarrow.DotNettySocket;\nusing System;\nusing System.Threading.Tasks;\n\nnamespace WebSocket.Server\n{\n    class Program\n    {\n        static async Task Main(string[] args)\n        {\n            var theServer = await SocketBuilderFactory.GetWebSocketServerBuilder(6002)\n                .OnConnectionClose((server, connection) =\u003e\n                {\n                    Console.WriteLine($\"连接关闭,连接名[{connection.ConnectionName}],当前连接数:{server.GetConnectionCount()}\");\n                })\n                .OnException(ex =\u003e\n                {\n                    Console.WriteLine($\"服务端异常:{ex.Message}\");\n                })\n                .OnNewConnection((server, connection) =\u003e\n                {\n                    connection.ConnectionName = $\"名字{connection.ConnectionId}\";\n                    Console.WriteLine($\"新的连接:{connection.ConnectionName},当前连接数:{server.GetConnectionCount()}\");\n                })\n                .OnRecieve((server, connection, msg) =\u003e\n                {\n                    Console.WriteLine($\"服务端:数据{msg}\");\n                    connection.Send(msg);\n                })\n                .OnSend((server, connection, msg) =\u003e\n                {\n                    Console.WriteLine($\"向连接名[{connection.ConnectionName}]发送数据:{msg}\");\n                })\n                .OnServerStarted(server =\u003e\n                {\n                    Console.WriteLine($\"服务启动\");\n                }).BuildAsync();\n\n            Console.ReadLine();\n        }\n    }\n}\n\n```\n- 控制台客户端\n``` c#\nusing Coldairarrow.DotNettySocket;\nusing System;\nusing System.Threading.Tasks;\n\nnamespace WebSocket.ConsoleClient\n{\n    class Program\n    {\n        static async Task Main(string[] args)\n        {\n            var theClient = await SocketBuilderFactory.GetWebSocketClientBuilder(\"127.0.0.1\", 6002)\n                .OnClientStarted(client =\u003e\n                {\n                    Console.WriteLine($\"客户端启动\");\n                })\n                .OnClientClose(client =\u003e\n                {\n                    Console.WriteLine($\"客户端关闭\");\n                })\n                .OnException(ex =\u003e\n                {\n                    Console.WriteLine($\"异常:{ex.Message}\");\n                })\n                .OnRecieve((client, msg) =\u003e\n                {\n                    Console.WriteLine($\"客户端:收到数据:{msg}\");\n                })\n                .OnSend((client, msg) =\u003e\n                {\n                    Console.WriteLine($\"客户端:发送数据:{msg}\");\n                })\n                .BuildAsync();\n\n            while (true)\n            {\n                await theClient.Send(Guid.NewGuid().ToString());\n\n                await Task.Delay(1000);\n            }\n        }\n    }\n}\n```\n- 网页客户端\n``` javascript\n\u003c!DOCTYPE HTML\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"utf-8\"\u003e\n    \u003ctitle\u003e菜鸟教程(runoob.com)\u003c/title\u003e\n\n    \u003cscript type=\"text/javascript\"\u003e\n        function WebSocketTest() {\n            if (\"WebSocket\" in window) {\n                var ws = new WebSocket(\"ws://127.0.0.1:6002\");\n\n                ws.onopen = function () {\n                    console.log('连上服务端');\n                    setInterval(function () {\n                        ws.send(\"111111\");\n                    }, 1000);\n                };\n\n                ws.onmessage = function (evt) {\n                    var received_msg = evt.data;\n                    console.log('收到' + received_msg);\n                };\n\n                ws.onclose = function () {\n                    console.log(\"连接已关闭...\");\n                };\n            }\n\n            else {\n                alert(\"您的浏览器不支持 WebSocket!\");\n            }\n        }\n    \u003c/script\u003e\n\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cdiv id=\"sse\"\u003e\n        \u003ca href=\"javascript:WebSocketTest()\"\u003e运行 WebSocket\u003c/a\u003e\n    \u003c/div\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n## UdpSocket\nUdp天生便是收发一体的，以下分为服务端与客户端仅仅是为了方便理解\n- 服务端\n``` c#\nusing Coldairarrow.DotNettySocket;\nusing System;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace UdpSocket.Server\n{\n    class Program\n    {\n        static async Task Main(string[] args)\n        {\n            var theServer = await SocketBuilderFactory.GetUdpSocketBuilder(6003)\n                .OnClose(server =\u003e\n                {\n                    Console.WriteLine($\"服务端关闭\");\n                })\n                .OnException(ex =\u003e\n                {\n                    Console.WriteLine($\"服务端异常:{ex.Message}\");\n                })\n                .OnRecieve((server, point, bytes) =\u003e\n                {\n                    Console.WriteLine($\"服务端:收到来自[{point.ToString()}]数据:{Encoding.UTF8.GetString(bytes)}\");\n                    server.Send(bytes, point);\n                })\n                .OnSend((server, point, bytes) =\u003e\n                {\n                    Console.WriteLine($\"服务端发送数据:目标[{point.ToString()}]数据:{Encoding.UTF8.GetString(bytes)}\");\n                })\n                .OnStarted(server =\u003e\n                {\n                    Console.WriteLine($\"服务端启动\");\n                }).BuildAsync();\n\n            Console.ReadLine();\n        }\n    }\n}\n\n```\n- 客户端\n``` c#\nusing Coldairarrow.DotNettySocket;\nusing System;\nusing System.Net;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace UdpSocket.Client\n{\n    class Program\n    {\n        static async Task Main(string[] args)\n        {\n            var theClient = await SocketBuilderFactory.GetUdpSocketBuilder()\n                .OnClose(server =\u003e\n                {\n                    Console.WriteLine($\"客户端关闭\");\n                })\n                .OnException(ex =\u003e\n                {\n                    Console.WriteLine($\"客户端异常:{ex.Message}\");\n                })\n                .OnRecieve((server, point, bytes) =\u003e\n                {\n                    Console.WriteLine($\"客户端:收到来自[{point.ToString()}]数据:{Encoding.UTF8.GetString(bytes)}\");\n                })\n                .OnSend((server, point, bytes) =\u003e\n                {\n                    Console.WriteLine($\"客户端发送数据:目标[{point.ToString()}]数据:{Encoding.UTF8.GetString(bytes)}\");\n                })\n                .OnStarted(server =\u003e\n                {\n                    Console.WriteLine($\"客户端启动\");\n                }).BuildAsync();\n\n            while (true)\n            {\n                await theClient.Send(Guid.NewGuid().ToString(), new IPEndPoint(IPAddress.Parse(\"127.0.0.1\"), 6003));\n                await Task.Delay(1000);\n            }\n        }\n    }\n}\n\n```\n\n# 结尾\n以上所有示例在源码中都有，若觉得不错请点赞加星星，希望能够帮助到大家。\n\n有任何问题请及时反馈或加群交流\n\nQQ群1:（已满） \n\nQQ群2:579202910\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FColdairarrow%2FDotNettySocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FColdairarrow%2FDotNettySocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FColdairarrow%2FDotNettySocket/lists"}