nanoFramework.System.Net.WebSockets 1.1.147

Prefix Reserved
dotnet add package nanoFramework.System.Net.WebSockets --version 1.1.147
                    
NuGet\Install-Package nanoFramework.System.Net.WebSockets -Version 1.1.147
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="nanoFramework.System.Net.WebSockets" Version="1.1.147" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="nanoFramework.System.Net.WebSockets" Version="1.1.147" />
                    
Directory.Packages.props
<PackageReference Include="nanoFramework.System.Net.WebSockets" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add nanoFramework.System.Net.WebSockets --version 1.1.147
                    
#r "nuget: nanoFramework.System.Net.WebSockets, 1.1.147"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=nanoFramework.System.Net.WebSockets&version=1.1.147
                    
Install nanoFramework.System.Net.WebSockets as a Cake Addin
#tool nuget:?package=nanoFramework.System.Net.WebSockets&version=1.1.147
                    
Install nanoFramework.System.Net.WebSockets as a Cake Tool

Quality Gate Status Reliability Rating License NuGet #yourfirstpr Discord

nanoFramework logo


Welcome to the .NET nanoFramework System.Net.WebSockets Library repository

This API mirrors (as close as possible) the official .NET System.Net.WebSockets. Exceptions are mainly derived from the lack of async and generics support in .NET nanoFramework.

Build status

Component Build Status NuGet Package
System.Net.WebSockets Build Status NuGet
System.Net.WebSockets.Client Build Status NuGet
System.Net.WebSockets.Server Build Status NuGet

Samples

WebSockets Server Sample

Server.RgbSample shows howto use Websocket Server with a Webserver hosting a WebApp that controlls the rgb led on an Atom Lite ESP32.

WebSockets Client Sample

Client.Sample shows how to use the Websocket Client.

WebSockets Server and Client sample

ServerClient.Sample shows how to configure and start a WebSocket Server and (ssl) Client.

Usage

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

Client

Connect to a websocket server

To 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. You 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.

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.

using System;
using System.Threading;
using System.Net.WebSockets;
using System.Net.WebSockets.WebSocketFrame;
using System.Text;

namespace NFWebsocketTestClient
{
    public class Program
    {
        public static void Main()
        {
            //setup WebSocketClient
            ClientWebSocket websocketClient = new ClientWebSocket(new ClientWebSocketOptions()
            {
                //Change the heart beat to a 30 second interval
                KeepAliveInterval = TimeSpan.FromSeconds(30)
            });

            //Handler for receiving websocket messages
            websocketClient.MessageReceived += WebsocketClient_MessageReceived;
            //Setup custom header
            var headers = new ClientWebSocketHeaders();
            headers["userId"] = "nano";

            //Connect the client to the websocket server with custom headers
            websocketClient.Connect("wss://websocket.nanoFramework.net", headers);

            //Send a message very 5 seconds
            while(websocketClient.State == System.Net.WebSockets.WebSocketFrame.WebSocketState.Open)
            {
                websocketClient.SendString("Hello nanoFramework Websocket!");
                Thread.Sleep(5000);
            }
        }

        private static void WebsocketClient_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            var client = (ClientWebSocket)sender;

            //If message is of type Text, echo message back to client
            if(e.Frame.MessageType == WebSocketMessageType.Text)
            {
                string message = Encoding.UTF8.GetString(e.Frame.Buffer, 0, e.Frame.MessageLength);
                client.SendString(message);
            }
        }
    }
}
Connection state

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

Receiving messages from server

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

Message frame

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

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.

Send messages

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

Closing a connection

The 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. Whenever a connection is closed the event Closed is fired.

Server

The 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 or WebServer. The server shares a common websocket base with the Client implementation.

Creating a server

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

If 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 or WebServer. To do this set the option IsStandAlone to false.

To start the websocket server simply call Start.

WebSocketServer wsServer = new WebSocketServer(new WebSocketServerOptions() { 
                MaxClients = 10,
                IsStandAlone = false
            });

wsServer.MessageReceived += WsServer_MessageReceived;
wsServer.Start();
Handling client connections

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

When using .NET nanoFramework HttpListner or 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.

//webserver receive message event handler
private static void WebServer_CommandReceived(object obj, WebServerEventArgs e)
{
    //check the path of the request
    if(e.Context.Request.RawUrl == "/ws")
    {
        //check if this is a websocket request or a page request 
        if(e.Context.Request.Headers["Upgrade"] == "websocket")
        {
            //Upgrade to a websocket
            _wsServer.AddWebSocket(e.Context);
        }
    }
}
Handling a new connection

When a client is connected the WebsocketOpened event is called. The WebserverEventArgs contains the endpoint of the client.

Handling connection closed

When a client connection is closed the WebsocketClosed event is called again containing the endpoint in the webserverEventArgs.

Closing a client connection

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

Receiving messages from clients

When a message from any client is received the MessageReceived is raised. Please see the Client section Receiving Messages and Message Frame on how to handle messages. The client who send the message can be identified by checking Endpoint property of the MessageFrame.

Sending messages

It'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.

Stopping the server

You can stop the websocket server by calling Stop.

Feedback and documentation

For documentation, providing feedback, issues and finding out how to contribute please refer to the Home repo.

Join our Discord community here.

Credits

The list of contributors to this project can be found at CONTRIBUTORS.

License

The nanoFramework Class Libraries are licensed under the MIT license.

Code of Conduct

This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behaviour in our community. For more information see the .NET Foundation Code of Conduct.

.NET Foundation

This project is supported by the .NET Foundation.

Product Compatible and additional computed target framework versions.
.NET Framework net is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on nanoFramework.System.Net.WebSockets:

Repository Stars
nanoframework/Samples
🍬 Code samples from the nanoFramework team used in testing, proof of concepts and other explorational endeavours
Version Downloads Last updated
1.1.147 151 6 days ago
1.1.146 150 6 days ago
1.1.145 467 13 days ago
1.1.144 450 13 days ago
1.1.143 182 a month ago
1.1.142 151 a month ago
1.1.141 153 a month ago
1.1.140 157 a month ago
1.1.139 162 a month ago
1.1.138 120 a month ago
1.1.137 94 a month ago
1.1.136 124 a month ago
1.1.135 93 a month ago
1.1.133 97 a month ago
1.1.132 93 a month ago
1.1.130 99 a month ago
1.1.129 89 a month ago
1.1.128 94 a month ago
1.1.127 96 a month ago
1.1.126 92 a month ago
1.1.125 155 2 months ago
1.1.124 94 2 months ago
1.1.123 98 2 months ago
1.1.122 102 2 months ago
1.1.121 100 2 months ago
1.1.120 111 2 months ago
1.1.118 95 2 months ago
1.1.117 94 2 months ago
1.1.116 108 2 months ago
1.1.112 95 2 months ago
1.1.111 85 2 months ago
1.1.109 166 3 months ago
1.1.108 119 3 months ago
1.1.105 357 6 months ago
1.1.102 191 8 months ago
1.1.101 89 8 months ago
1.1.98 260 5/13/2024
1.1.96 116 5/13/2024
1.1.94 198 5/10/2024
1.1.92 213 4/9/2024
1.1.90 139 4/8/2024
1.1.88 169 4/3/2024
1.1.86 140 4/3/2024
1.1.84 411 1/29/2024
1.1.82 294 1/26/2024
1.1.80 300 1/24/2024
1.1.78 341 1/20/2024
1.1.75 641 11/10/2023
1.1.72 455 11/9/2023
1.1.70 470 11/3/2023
1.1.68 555 10/10/2023
1.1.66 505 10/10/2023
1.1.64 502 10/4/2023
1.1.62 618 9/4/2023
1.1.60 584 9/4/2023
1.1.57 904 5/19/2023
1.1.52 898 2/17/2023
1.1.50 869 1/24/2023
1.1.48 862 12/28/2022
1.1.45 871 12/27/2022
1.1.41 990 11/23/2022
1.1.39 1,004 10/26/2022
1.1.37 913 10/26/2022
1.1.35 916 10/26/2022
1.1.33 938 10/25/2022
1.1.30 958 10/24/2022
1.1.28 978 10/23/2022
1.1.26 948 10/23/2022
1.1.23 943 10/10/2022
1.1.21 910 10/8/2022
1.1.19 948 10/8/2022
1.1.16 989 9/22/2022
1.1.14 1,011 9/22/2022
1.1.12 966 9/22/2022
1.1.10 1,015 9/22/2022
1.1.8 1,065 9/15/2022
1.1.6 1,056 8/5/2022
1.1.5 990 8/4/2022
1.1.4 971 8/4/2022
1.1.2 976 8/4/2022
1.0.1.25 1,054 6/13/2022
1.0.1.23 977 6/9/2022
1.0.1.21 1,004 6/8/2022
1.0.1.19 1,004 5/27/2022
1.0.1.17 945 5/26/2022
1.0.1.15 1,003 5/19/2022
1.0.1.13 949 5/18/2022
1.0.1.11 1,007 5/4/2022
1.0.1.9 958 5/3/2022
1.0.1 1,018 3/29/2022
1.0.0-preview.99 155 3/29/2022
1.0.0-preview.98 140 3/28/2022
1.0.0-preview.97 141 3/28/2022
1.0.0-preview.96 150 3/28/2022
1.0.0-preview.95 139 3/28/2022
1.0.0-preview.94 154 3/17/2022
1.0.0-preview.93 147 3/17/2022
1.0.0-preview.92 144 3/14/2022
1.0.0-preview.91 140 3/14/2022
1.0.0-preview.90 140 3/14/2022
1.0.0-preview.89 146 3/14/2022
1.0.0-preview.88 146 3/14/2022
1.0.0-preview.87 144 3/14/2022
1.0.0-preview.86 143 3/9/2022
1.0.0-preview.85 156 3/5/2022
1.0.0-preview.84 162 3/4/2022
1.0.0-preview.83 146 3/3/2022
1.0.0-preview.82 146 3/1/2022
1.0.0-preview.81 150 2/25/2022
1.0.0-preview.80 149 2/18/2022
1.0.0-preview.77 150 2/17/2022
1.0.0-preview.75 150 2/12/2022
1.0.0-preview.74 145 2/7/2022
1.0.0-preview.73 164 2/6/2022
1.0.0-preview.72 163 2/5/2022
1.0.0-preview.71 171 2/4/2022
1.0.0-preview.70 164 2/4/2022
1.0.0-preview.69 161 1/28/2022
1.0.0-preview.68 161 1/28/2022
1.0.0-preview.67 169 1/28/2022
1.0.0-preview.65 182 1/21/2022
1.0.0-preview.64 164 1/21/2022
1.0.0-preview.63 169 1/21/2022
1.0.0-preview.62 159 1/21/2022
1.0.0-preview.61 162 1/21/2022
1.0.0-preview.60 160 1/21/2022
1.0.0-preview.59 162 1/15/2022
1.0.0-preview.58 161 1/13/2022
1.0.0-preview.57 163 1/13/2022
1.0.0-preview.52 162 1/12/2022
1.0.0-preview.50 168 1/6/2022
1.0.0-preview.48 161 12/31/2021
1.0.0-preview.47 236 12/20/2021
1.0.0-preview.40 187 12/5/2021
1.0.0-preview.38 173 12/2/2021
1.0.0-preview.36 180 12/1/2021
1.0.0-preview.33 202 10/27/2021
1.0.0-preview.26 211 6/1/2021
1.0.0-preview.24 217 5/24/2021
1.0.0-preview.20 192 4/6/2021