Websockets
The websocket handler integratesFleck to upgrade client connections so that youcan use websocket functionality in your application.
ℹ️
A project serving a websocket can quickly be created by using aproject template.
The following example hosts a simple console application that provides a websocket server that will echo received messages backto connected clients:
using GenHTTP.Engine.Internal;using GenHTTP.Modules.Practices;using GenHTTP.Modules.Websockets;var allSockets =new List<IWebsocketConnection>();var websocket = Websocket.Create() .OnOpen((socket) => { Console.WriteLine("Open!"); allSockets.Add(socket); }) .OnClose((socket) => { Console.WriteLine("Close!"); allSockets.Remove(socket); }) .OnMessage((socket, message) => { Console.WriteLine(message); allSockets.ToList().ForEach(s => s.Send("Echo: " + message)); });var host = Host.Create() .Handler(websocket) .Defaults() .Development() .Console();await host.StartAsync();var input = Console.ReadLine();while (input !="exit"){if (input !=null) {foreach (var socketin allSockets.ToList()) {await socket.Send(input); } } input = Console.ReadLine();}await host.StopAsync();
After starting the server, you can open the following HTML page (provided by the Fleck project as a sample)in your browser to connect to the server:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head> <title>websocket client</title> <scripttype="text/javascript">varstart=function () {varinc= document.getElementById('incomming');varwsImpl= window.WebSocket|| window.MozWebSocket;varform= document.getElementById('sendForm');varinput= document.getElementById('sendText');inc.innerHTML+="connecting to server ..<br/>";// create a new websocket and connect window.ws=newwsImpl('ws://localhost:8080/');// when data is comming from the server, this metod is calledws.onmessage=function (evt) {inc.innerHTML+=evt.data+'<br/>'; };// when the connection is established, this method is calledws.onopen=function () {inc.innerHTML+='.. connection open<br/>'; };// when the connection is closed, this method is calledws.onclose=function () {inc.innerHTML+='.. connection closed<br/>'; }form.addEventListener('submit',function(e){e.preventDefault();varval=input.value;ws.send(val);input.value="";}); } window.onload=start; </script></head><body><formid="sendForm"><inputid="sendText"placeholder="Text to send" /></form> <preid="incomming"></pre></body></html>
Every browser instance of this page will connect to the server and show messages entered in theserver app or any other browser window.