{"id":19244331,"url":"https://github.com/nanoframework/system.net.websockets","last_synced_at":"2026-05-14T09:05:17.272Z","repository":{"id":37977422,"uuid":"350100933","full_name":"nanoframework/System.Net.WebSockets","owner":"nanoframework","description":"📦 System.Net.WebSockets implementation for .NET nanoFramework","archived":false,"fork":false,"pushed_at":"2025-04-02T12:46:23.000Z","size":469,"stargazers_count":14,"open_issues_count":0,"forks_count":7,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-04-19T17:54:22.510Z","etag":null,"topics":["csharp","dotnet","embedded-systems","hacktoberfest","websocket-client","websocket-server","websockets"],"latest_commit_sha":null,"homepage":"https://www.nanoframework.net","language":"C#","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nanoframework.png","metadata":{"funding":{"open_collective":"nanoframework","github":"nanoframework"},"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","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,"zenodo":null}},"created_at":"2021-03-21T19:42:21.000Z","updated_at":"2025-04-02T12:38:22.000Z","dependencies_parsed_at":"2023-10-16T03:29:09.371Z","dependency_job_id":"d583d326-9bfc-4cf4-8768-6b15350aa7e1","html_url":"https://github.com/nanoframework/System.Net.WebSockets","commit_stats":{"total_commits":280,"total_committers":7,"mean_commits":40.0,"dds":0.6357142857142857,"last_synced_commit":"9240fa6f5c50b6657d7348e9ed8376ff522eb93b"},"previous_names":[],"tags_count":140,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nanoframework%2FSystem.Net.WebSockets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nanoframework%2FSystem.Net.WebSockets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nanoframework%2FSystem.Net.WebSockets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nanoframework%2FSystem.Net.WebSockets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nanoframework","download_url":"https://codeload.github.com/nanoframework/System.Net.WebSockets/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250032464,"owners_count":21363839,"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":["csharp","dotnet","embedded-systems","hacktoberfest","websocket-client","websocket-server","websockets"],"created_at":"2024-11-09T17:22:57.825Z","updated_at":"2026-05-14T09:05:12.230Z","avatar_url":"https://github.com/nanoframework.png","language":"C#","funding_links":["https://opencollective.com/nanoframework","https://github.com/sponsors/nanoframework"],"categories":[],"sub_categories":[],"readme":"[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=nanoframework_nanoframework.System.Net.WebSockets\u0026metric=alert_status)](https://sonarcloud.io/dashboard?id=nanoframework_nanoframework.System.Net.WebSockets) [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=nanoframework_nanoframework.System.Net.WebSockets\u0026metric=reliability_rating)](https://sonarcloud.io/dashboard?id=nanoframework_nanoframework.System.Net.WebSockets) [![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) [![NuGet](https://img.shields.io/nuget/dt/nanoFramework.System.Net.WebSockets.svg?label=NuGet\u0026style=flat\u0026logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.Net.WebSockets/) [![#yourfirstpr](https://img.shields.io/badge/first--timers--only-friendly-blue.svg)](https://github.com/nanoframework/Home/blob/main/CONTRIBUTING.md) [![Discord](https://img.shields.io/discord/478725473862549535.svg?logo=discord\u0026logoColor=white\u0026label=Discord\u0026color=7289DA)](https://discord.gg/gCyBu8T)\n\n![nanoFramework logo](https://raw.githubusercontent.com/nanoframework/Home/main/resources/logo/nanoFramework-repo-logo.png)\n\n-----\n\n# Welcome to the .NET **nanoFramework** System.Net.WebSockets Library repository\n\nThis API mirrors (as close as possible) the official .NET [System.Net.WebSockets](https://docs.microsoft.com/en-us/dotnet/api/system.net.websockets.clientwebsocket). Exceptions are mainly derived from the lack of `async` and generics support in .NET **nanoFramework**.\n\n## Build status\n\n| Component | Build Status | NuGet Package |\n|:-|---|---|\n| System.Net.WebSockets | [![Build Status](https://dev.azure.com/nanoframework/System.Net.Websockets/_apis/build/status/nanoFramework.System.Net.Websockets?repoName=nanoframework%2FSystem.Net.WebSockets\u0026branchName=main)](https://dev.azure.com/nanoframework/System.Net.Websockets/_build/latest?definitionId=70\u0026repoName=nanoframework%2FSystem.Net.WebSockets\u0026branchName=main) | [![NuGet](https://img.shields.io/nuget/v/nanoFramework.System.Net.WebSockets.svg?label=NuGet\u0026style=flat\u0026logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.Net.WebSockets/) |\n| System.Net.WebSockets.Client | [![Build Status](https://dev.azure.com/nanoframework/System.Net.Websockets/_apis/build/status/nanoFramework.System.Net.Websockets?repoName=nanoframework%2FSystem.Net.WebSockets\u0026branchName=main)](https://dev.azure.com/nanoframework/System.Net.Websockets/_build/latest?definitionId=70\u0026repoName=nanoframework%2FSystem.Net.WebSockets\u0026branchName=main) | [![NuGet](https://img.shields.io/nuget/v/nanoFramework.System.Net.WebSockets.Client.svg?label=NuGet\u0026style=flat\u0026logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.Net.WebSockets.Client/) |\n| System.Net.WebSockets.Server | [![Build Status](https://dev.azure.com/nanoframework/System.Net.Websockets/_apis/build/status/nanoFramework.System.Net.Websockets?repoName=nanoframework%2FSystem.Net.WebSockets\u0026branchName=main)](https://dev.azure.com/nanoframework/System.Net.Websockets/_build/latest?definitionId=70\u0026repoName=nanoframework%2FSystem.Net.WebSockets\u0026branchName=main) | [![NuGet](https://img.shields.io/nuget/v/nanoFramework.System.Net.WebSockets.Server.svg?label=NuGet\u0026style=flat\u0026logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.Net.WebSockets.Server/) |\n\n## Samples\n\n### WebSockets Server Sample\n\n[Server.RgbSample](https://github.com/nanoframework/Samples/tree/main/samples/WebSockets/WebSockets.Server.RgbSample) shows howto use Websocket Server with a Webserver hosting a WebApp that controlls the rgb led on an Atom Lite ESP32.\n\n### WebSockets Client Sample\n\n[Client.Sample](https://github.com/nanoframework/Samples/tree/main/samples/WebSockets/Websockets.ServerClient.Sample) shows how to use the Websocket Client.\n\n### WebSockets Server and Client sample\n\n[ServerClient.Sample](https://github.com/nanoframework/Samples/tree/main/samples/WebSockets/Websockets.ServerClient.Sample) shows how to configure and start a WebSocket Server and (ssl) Client.\n\n## Usage\n\nThis is a Websocket Client and Server library for .NET nanoFramework. Websockets are mainly used for creating interactive web apps that require a constant connection with the webserver. In the Internet of Things domain, some protocols require a WebSocket connection, like SignalR. Some IoT servers also support or require protocols like MQTT to run over websockets.  \n\n### Client\n\n#### Connect to a websocket server\n\nTo connect to a websocket server, create a `ClientWebsocket`. You can set extra websocket options by adding `ClientWebSocketOptions` upon initialization. These options can be used to set specific SSL options, change keep alive interval, server timeout and set maximum send and receive message size. \nYou can start the connection by calling `Connect` with the uri of the websocket server. A websocket location always begins with `ws://` or `wss://`. You can use the optional `ClientWebSocketHeaders` to set specific headers. \n\n\u003e Note: The ClientWebSocketOptions.MaxFragmentSize sets the max package size of the outgoing messages. When sending a message that exceeds the maximum package size. The message will be automatically chunked into smaller messages. \n\n```csharp\nusing System;\nusing System.Threading;\nusing System.Net.WebSockets;\nusing System.Net.WebSockets.WebSocketFrame;\nusing System.Text;\n\nnamespace NFWebsocketTestClient\n{\n    public class Program\n    {\n        public static void Main()\n        {\n            //setup WebSocketClient\n            ClientWebSocket websocketClient = new ClientWebSocket(new ClientWebSocketOptions()\n            {\n                //Change the heart beat to a 30 second interval\n                KeepAliveInterval = TimeSpan.FromSeconds(30)\n            });\n\n            //Handler for receiving websocket messages\n            websocketClient.MessageReceived += WebsocketClient_MessageReceived;\n            //Setup custom header\n            var headers = new ClientWebSocketHeaders();\n            headers[\"userId\"] = \"nano\";\n\n            //Connect the client to the websocket server with custom headers\n            websocketClient.Connect(\"wss://websocket.nanoFramework.net\", headers);\n\n            //Send a message very 5 seconds\n            while(websocketClient.State == System.Net.WebSockets.WebSocketFrame.WebSocketState.Open)\n            {\n                websocketClient.SendString(\"Hello nanoFramework Websocket!\");\n                Thread.Sleep(5000);\n            }\n        }\n\n        private static void WebsocketClient_MessageReceived(object sender, MessageReceivedEventArgs e)\n        {\n            var client = (ClientWebSocket)sender;\n\n            //If message is of type Text, echo message back to client\n            if(e.Frame.MessageType == WebSocketMessageType.Text)\n            {\n                string message = Encoding.UTF8.GetString(e.Frame.Buffer, 0, e.Frame.MessageLength);\n                client.SendString(message);\n            }\n        }\n    }\n}\n```\n\n#### Connection state\n\nThe connection state can be monitored by checking the ClientWebSocket `State`. After the connection is established the state is set to `Open`. The client is only able to send messages if  the state is Open. \n\n#### Receiving messages from server\n\nMessages can be received by setting an event handler for `MessageReceived`. This handler will be called every time a message is received. The  `MesageReceivedArguments` contains the `MessageReceivedFrame` with a buffer containing the message.  \n\n##### Message frame\n\nWebsockets `MessageReceivedFrame` support two types of messages: `Text` and `Binary`. The property `MessageType` tells what type of message is received. `EndPoint` contains the IPEndPoind of the message sender. The `Buffer` contains the actual information that was send. \n\n\u003e Note: To be able to receive fragmented messages the user needs to implement there own logic. By checking IsFragmented you are able to see if you're dealing with a fragmented message. The property Fragmentation tells if you are dealing with the begin, middle or end fragment of a message. \n\n#### Send messages\n\nA message can be send by calling `SendString` for a text message or `SendBytes` for sending a binary message using a byte array. You can also call `Send` that takes a byte array and a `MessageType` as arguments. \n\n#### Closing a connection\n\nThe connection can be closed by calling `Close`. Calling this method will send a closing message over the line. You can optional specify a `WebSocketCloseStatus` and description on the reason for closing for debugging purposes. \nWhenever a connection is closed the event `Closed` is fired.  \n\n### Server\n\nThe `WebSocketServer` is a websocket host for .NET nanoFramework that can handle multiple websocket connections. The server can be run stand alone or be integrated with the nanoFramework [HttpListner](https://github.com/nanoframework/System.Net.Http/blob/develop/nanoFramework.System.Net.Http/Http/System.Net.HttpListener.cs) or [WebServer](https://github.com/nanoframework/nanoFramework.WebServer). \nThe server shares a common websocket base with the Client implementation. \n\n#### Creating a server\n\nTo start a new server, create a `WebsocketServer` with optional `WebSocketServerOptions`. By default this will start a selfhosted server on port 80, by setting the `Prefix` and `Port` options you can specify on what port and what prefix this server will listen. The default prefix is `/`. It's recommended to set the `MaxClients` to make sure the server does not run out of resources.\n\nIf you want to host a webapp to interact with the websocket server, it's best to integrate the websocket server directly with .NET nanoFramework [HttpListner](https://github.com/nanoframework/System.Net.Http/blob/develop/nanoFramework.System.Net.Http/Http/System.Net.HttpListener.cs) or [WebServer](https://github.com/nanoframework/nanoFramework.WebServer). To do this set the option `IsStandAlone` to `false`. \n\nTo start the websocket server simply call `Start`.\n\n```csharp\nWebSocketServer wsServer = new WebSocketServer(new WebSocketServerOptions() { \n                MaxClients = 10,\n                IsStandAlone = false\n            });\n\nwsServer.MessageReceived += WsServer_MessageReceived;\nwsServer.Start();\n```\n\n#### Handling client connections\n\nWhen the websocket server is selfhosted the client connections are handled automatically and added to the websocket server client pool. You can check the number of connected clients with `ClientsCount`. Calling `ListClients` will return an array of all Ip Endpoints of the connected clients. \n\nWhen using .NET nanoFramework [HttpListner](https://github.com/nanoframework/System.Net.Http/blob/develop/nanoFramework.System.Net.Http/Http/System.Net.HttpListener.cs) or [WebServer](https://github.com/nanoframework/nanoFramework.WebServer) you can upgrade a websocket request by passing the `HttpListnerContext` to the websocket server by calling `AddWebSocket`. If the connection is successful established `AddWebsocket` will return `true`. \n\n```csharp\n//webserver receive message event handler\nprivate static void WebServer_CommandReceived(object obj, WebServerEventArgs e)\n{\n    //check the path of the request\n    if(e.Context.Request.RawUrl == \"/ws\")\n    {\n        //check if this is a websocket request or a page request \n        if(e.Context.Request.Headers[\"Upgrade\"] == \"websocket\")\n        {\n            //Upgrade to a websocket\n            _wsServer.AddWebSocket(e.Context);\n        }\n    }\n}\n```\n\n##### Handling a new connection\n\nWhen a client is connected the `WebsocketOpened` event is called. The `WebserverEventArgs` contains the endpoint of the client.\n\n##### Handling connection closed\n\nWhen a client connection is closed the `WebsocketClosed` event is called again containing the endpoint in the `webserverEventArgs`. \n\n#### Closing a client connection\n\nYou can close a specific client connection by calling `DisconnectClient`. You need to specify what client you want to disconnect by providing the client endpoint. Also you need to specify an appropriate `WebSocketCloseStatus`.\n\n#### Receiving messages from clients\n\nWhen a message from any client is received the `MessageReceived` is raised. Please see the Client section [Receiving Messages](#receiving_messages) and [Message Frame](#message_frame) on how to handle messages. The client who send the message can be identified by checking `Endpoint` property of the `MessageFrame`.  \n\n#### Sending messages\n\nIt's possible to send a messages to a specific client by calling `SendString` for a text message or `SendData` for sending a binary message using a byte array. You need to specify the specific client `EndPoint` that you want to send the message to. If you want to send a message to all clients you can simply use `Broadcast` and provide a byte array or a string. \n\n#### Stopping the server\n\nYou can stop the websocket server by calling `Stop`.\n\n## Feedback and documentation\n\nFor documentation, providing feedback, issues and finding out how to contribute please refer to the [Home repo](https://github.com/nanoframework/Home).\n\nJoin our Discord community [here](https://discord.gg/gCyBu8T).\n\n## Credits\n\nThe list of contributors to this project can be found at [CONTRIBUTORS](https://github.com/nanoframework/Home/blob/main/CONTRIBUTORS.md).\n\n## License\n\nThe **nanoFramework** Class Libraries are licensed under the [MIT license](LICENSE.md).\n\n## Code of Conduct\n\nThis project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behaviour in our community.\nFor more information see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).\n\n## .NET Foundation\n\nThis project is supported by the [.NET Foundation](https://dotnetfoundation.org).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnanoframework%2Fsystem.net.websockets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnanoframework%2Fsystem.net.websockets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnanoframework%2Fsystem.net.websockets/lists"}