Skip to content

Commit 6009db3

Browse files
authored
Added documentation to the readme (#41)
***NO_CI***
1 parent 1c6dd96 commit 6009db3

File tree

1 file changed

+158
-0
lines changed

1 file changed

+158
-0
lines changed

README.md

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,164 @@ This API mirrors (as close as possible) the official .NET [System.Net.WebSockets
1919
| System.Net.WebSockets.Server | [![Build Status](https://dev.azure.com/nanoframework/System.Net.Websockets/_apis/build/status/nanoframework.nanoframework.System.Net.Websockets?branchName=main)](https://dev.azure.com/nanoframework/System.Net.Websockets/_build/latest?definitionId=70&branchName=main) | [![NuGet](https://img.shields.io/nuget/v/nanoFramework.System.Net.WebSockets.Server.svg?label=NuGet&style=flat&logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.Net.WebSockets.Server/) |
2020
| System.Net.WebSockets.Server (preview) |[![Build Status](https://dev.azure.com/nanoframework/System.Net.Websockets/_apis/build/status/nanoframework.nanoframework.System.Net.Websockets?branchName=develop)](https://dev.azure.com/nanoframework/System.Net.Websockets/_build/latest?definitionId=70&branchName=develop) | [![NuGet](https://img.shields.io/nuget/vpre/nanoFramework.System.Net.WebSockets.Server.svg?label=NuGet&style=flat&logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.Net.WebSockets.Server/) |
2121

22+
## Usage
23+
24+
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.
25+
26+
### Client
27+
28+
#### Connect to a websocket server
29+
30+
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.
31+
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.
32+
33+
> 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.
34+
35+
```csharp
36+
using System;
37+
using System.Threading;
38+
using System.Net.WebSockets;
39+
using System.Net.WebSockets.WebSocketFrame;
40+
using System.Text;
41+
42+
namespace NFWebsocketTestClient
43+
{
44+
public class Program
45+
{
46+
public static void Main()
47+
{
48+
//setup WebSocketClient
49+
ClientWebSocket websocketClient = new ClientWebSocket(new ClientWebSocketOptions()
50+
{
51+
//Change the heart beat to a 30 second interval
52+
KeepAliveInterval = TimeSpan.FromSeconds(30)
53+
});
54+
55+
//Handler for receiving websocket messages
56+
websocketClient.MessageReceived += WebsocketClient_MessageReceived;
57+
//Setup custom header
58+
var headers = new ClientWebSocketHeaders();
59+
headers["userId"] = "nano";
60+
61+
//Connect the client to the websocket server with custom headers
62+
websocketClient.Connect("wss://websocket.nanoFramework.net", headers);
63+
64+
//Send a message very 5 seconds
65+
while(websocketClient.State == System.Net.WebSockets.WebSocketFrame.WebSocketState.Open)
66+
{
67+
websocketClient.SendString("Hello nanoFramework Websocket!");
68+
Thread.Sleep(5000);
69+
}
70+
}
71+
72+
private static void WebsocketClient_MessageReceived(object sender, MessageReceivedEventArgs e)
73+
{
74+
var client = (ClientWebSocket)sender;
75+
76+
//If message is of type Text, echo message back to client
77+
if(e.Frame.MessageType == WebSocketMessageType.Text)
78+
{
79+
string message = Encoding.UTF8.GetString(e.Frame.Buffer, 0, e.Frame.MessageLength);
80+
client.SendString(message);
81+
}
82+
}
83+
}
84+
}
85+
```
86+
87+
#### Connection state
88+
89+
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.
90+
91+
#### Receiving messages
92+
93+
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.
94+
95+
##### Message frame
96+
97+
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.
98+
99+
> 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.
100+
101+
#### Send messages
102+
103+
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.
104+
105+
#### Closing a connection
106+
107+
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.
108+
Whenever a connection is closed the event `Closed` is fired.
109+
110+
### Server
111+
112+
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](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).
113+
The server shares a common websocket base with the Client implementation.
114+
115+
#### Creating a server
116+
117+
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.
118+
119+
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](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`.
120+
121+
To start the websocket server simply call `Start`.
122+
123+
```csharp
124+
WebSocketServer wsServer = new WebSocketServer(new WebSocketServerOptions() {
125+
MaxClients = 10,
126+
IsStandAlone = false
127+
});
128+
129+
wsServer.MessageReceived += WsServer_MessageReceived;
130+
wsServer.Start();
131+
```
132+
133+
#### Handling client connections
134+
135+
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.
136+
137+
When 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`.
138+
139+
```csharp
140+
//webserver receive message event handler
141+
private static void WebServer_CommandReceived(object obj, WebServerEventArgs e)
142+
{
143+
//check the path of the request
144+
if(e.Context.Request.RawUrl == "/ws")
145+
{
146+
//check if this is a websocket request or a page request
147+
if(e.Context.Request.Headers["Upgrade"] == "websocket")
148+
{
149+
//Upgrade to a websocket
150+
_wsServer.AddWebSocket(e.Context);
151+
}
152+
}
153+
}
154+
```
155+
156+
##### Handling a new connection
157+
158+
When a client is connected the `WebsocketOpened` event is called. The `WebserverEventArgs` contains the endpoint of the client.
159+
160+
##### Handling connection closed
161+
162+
When a client connection is closed the `WebsocketClosed` event is called again containing the endpoint in the `webserverEventArgs`.
163+
164+
#### Closing a client connection
165+
166+
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`.
167+
168+
#### Receiving messages
169+
170+
When 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`.
171+
172+
#### Sending messages
173+
174+
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.
175+
176+
#### Stopping the server
177+
178+
You can stop the websocket server by calling `Stop`.
179+
22180
## Feedback and documentation
23181

24182
For documentation, providing feedback, issues and finding out how to contribute please refer to the [Home repo](https://github.com/nanoframework/Home).

0 commit comments

Comments
 (0)