tesses.webserver.websocket/README.md

90 lines
3.8 KiB
Markdown

Finally Websockets specifically for Tesses.WebServer
====================================================
I implemented websockets for [Tesses.WebServer](https://gitlab.tesses.net/tesses50/tesses.webserver)
How To Use (Class inheriting from Server)
==========================================
public class SomeClass : Server
{
public override async Task GetAsync(ServerContext ctx)
{
await ctx.StartWebSocketConnectionAsync(async(sendMessage,ping,token)=>{
await sendMessage(WebSocketMessage.Create("Greetings"));
//send messages from here or add sendMessage to List<Func<WebSocketMessage,Task>>
while(!token.IsCancellationRequested)
{
await Task.Delay(100); //you might want to ping here too await ping(new byte[]{42,42,42,42});
}
},async(message)=>{
//message
bool isBinary=message.Binary;
if(isBinary)
{
byte[] data = message.Data;
}else{
string text = message.Text;
//or SomeType data = message.DecodeJson<SomeType>(); for json Data
}
},(clean)=>{
//the socket is closed
//clean means clean exit
});
}
}
How To Use (RoutableServer)
==============================
routable.Add("/socket",async(ctx)=>{
await ctx.StartWebSocketConnectionAsync(async(sendMessage,ping,token)=>{
await sendMessage(WebSocketMessage.Create("Greetings"));
//send messages from here or add sendMessage to List&lt;Func&lt;WebSocketMessage,Task&gt;&gt;
while(!token.IsCancellationRequested)
{
await Task.Delay(100); //you might want to ping here too await ping(new byte[]{42,42,42,42});
}
},async(message)=>{
//message
bool isBinary=message.Binary;
if(isBinary)
{
byte[] data = message.Data;
}else{
string text = message.Text;
//or SomeType data = message.DecodeJson<SomeType>(); for json Data
}
},(clean)=>{
//the socket is closed
//clean means clean exit
});
});
How To Use (SwagmeServer)
=========================
swagme.Add("/socket",async(ctx)=>{
await ctx.StartWebSocketConnectionAsync(async(sendMessage,ping,token)=>{
await sendMessage(WebSocketMessage.Create("Greetings"));
//send messages from here or add sendMessage to List&lt;Func&lt;WebSocketMessage,Task&gt;&gt;
while(!token.IsCancellationRequested)
{
await Task.Delay(100); //you might want to ping here too await ping(new byte[]{42,42,42,42});
}
},async(message)=>{
//message
bool isBinary=message.Binary;
if(isBinary)
{
byte[] data = message.Data;
}else{
string text = message.Text;
//or SomeType data = message.DecodeJson<SomeType>(); for json Data
}
},(clean)=>{
//the socket is closed
//clean means clean exit
});
},,new SwagmeDocumentation("WebSocket endpoint","A cool websocket endpoint"),group: "Real time comms");