DEV Community

syabuo
syabuo

Posted on

Try WebSocketServer csharp

Introduction

  • Tried to implement a WebSocket server using C # and send push notifications to the browser.
  • Don't use IIS and use System.Net.WebSockets to implement.
  • Referred to MSDN Articles

Server Source

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebSocketServerSample02
{
    class Program
    {
        static void Main(string[] args)
        {
            Run();
            Console.ReadKey();
        }

        static async Task Run()
        {
            HttpListener s = new HttpListener();
            s.Prefixes.Add("http://IPアドレス:ポート番号/");
            s.Start();
            Console.WriteLine("サーバ起動");

            var hc = await s.GetContextAsync();
            if (!hc.Request.IsWebSocketRequest)
            {
                hc.Response.StatusCode = 400;
                hc.Response.Close();
                return;
            }
            var wsc = await hc.AcceptWebSocketAsync(null);
            var ws = wsc.WebSocket;
            for (int i = 0; i != 5; ++i)
            {
                await Task.Delay(2000);
                var response = "push_event " + DateTime.Now.ToLongTimeString();
                var buffer = Encoding.UTF8.GetBytes(response);
                var segment = new ArraySegment<byte>(buffer);
                await ws.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
            }
            await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
        }
    }
}
  • Start HTTP server using HttpListener.
  • Wait for WebSocket connection receive request with GetContextAsync().
  • Refer to Request.IsWebSocketRequest and return status code 400 if not WebSocket connection.
  • Enable WebSocket connection with AcceptWebSocketAsync(null).

Send to client

            var ws = wsc.WebSocket;
            for (int i = 0; i != 5; ++i)
            {
                await Task.Delay(2000);
                var response = "push_event " + DateTime.Now.ToLongTimeString();
                var buffer = Encoding.UTF8.GetBytes(response);
                var segment = new ArraySegment<byte>(buffer);
                await ws.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
            }
            await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
  • Store the value of "push_event current time" to the client in response.
  • Send to client with SendAsync.

Client Source

  • WebSocket.onmessage processing operates when data comes from the server.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocketClient</title>
<script src="js/jquery-1.11.3.js"></script>
<script type="text/javascript">
    var webSocket;
    window.onload = function() {
        url = "http://IPアドレス:ポート番号/";
        webSocket = new WebSocket(url.replace("http://", "ws://").replace("https://", "wss://"));
        var messageArea = document.getElementById("messageArea");
        var appendMessage = function(value, color) {
            var messageElement = document.createElement("div");
            messageElement.style.color = color;
            messageElement.innerText = value;
            messageArea.insertBefore(messageElement, messageArea.firstChild);
        }
        webSocket.onopen = function() {
            appendMessage("Opened", "blue");
        }
        webSocket.onclose = function() {
            appendMessage("Closed", "red");
        }
        webSocket.onmessage = function(message) {
            var data = message.data;
            alert(data);
            appendMessage(data, "black");
        }
        webSocket.onerror = function(message) {
            appendMessage(message, "red");
        }
    }
</script>
</head>
<body>
    <div id="messageArea"></div>
</body>
</html

Top comments (0)