纯静态HTML 与 C# Server 进行WebSocket 链接

TODO: 这篇文章只是写了一个DEMO,告诉你如何使用C#构建一个WebSocket服务器,以便HTML网页能够经过WebSocket与之进行交互。

将会使用到的 Package:
websocket-sharp
Newtonsoft.JSONhtml

这个DEMO主要完成的工做是:web

  1. HTML 链接 WebSocket 并传送一个Json,Json包含两个数字a和b。
  2. 服务器监听 WebSocket 并解析Json里面的两个数字,将两个数字加起来的和做为结果以Json的形式传送给HTML。
  3. HTML 获得返回之后更新显示。
  4. 10秒以后,服务器主动向浏览器再发送一次消息。

补充说明:
普通的HTTP请求跟WebSocket请求有什么不同呢?为何咱们要用Websocket来链接?
我这里写的这个例子可能不是很好体现出Websocket的优点。
先说说它俩的不一样。ajax

  • HTTP是由客户端发起请求,服务器对请求进行处理以后作出相应的过程。
  • WebSocket跟Socket同样,一旦创建链接,服务器能够经过WebSocket主动向客户端发送数据。

好比例子中,第一个例子是对客户端上传的数据进行了处理,处理结果进行了返回,同时也延迟10s,让服务器端主动发送了一则消息。
虽然也能够用循环ajax轮询去实现相似服务器推送的效果,可是WebSocket会更省网络资源~json

clipboard.png

准备姿式

新建工程

首先须要准备两个工程:浏览器

  • 一个是Web项目,能够是任何Web项目,由于咱们只用到HTML。HTML单文件也是没有问题的。这里我用的是vscode live server。
  • 另外一个是C#命令行项目,固然也能够不是命令行,只是以为命令行比较方便,DEMO也不须要窗体,若是你须要窗体能够使用WPF或者WinForms。

必要依赖

  • 在C#项目中,咱们须要安装Nuget包:WebSocketSharp (因为这个Nuget包在写文的时候仍是rc,因此须要勾选包括抢鲜版才会搜索出来哦)和 Newtonsoft.JSON

Nuget安装

服务器代码

首先咱们须要新建一个类,做为一个app,去处理传送来的消息。服务器

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace WebSocketDemo
{
    class Add : WebSocketBehavior
    {
        protected override void OnOpen()
        {
            Console.WriteLine("Connection Open");
            base.OnOpen();
        }
        protected override void OnMessage(MessageEventArgs e)
        {
            var data = e.Data;
            if (TestJson(data))
            {
                var param = JToken.Parse(data);
                if (param["a"] != null && param["b"] != null)
                {
                    var a = param["a"].ToObject<int>();
                    var b = param["b"].ToObject<int>();
                    Send(JsonConvert.SerializeObject(new { code = 200, msg = "result is " + (a + b) }));
                    Task.Factory.StartNew(() => {
                        Task.Delay(10000).Wait();
                        Send(JsonConvert.SerializeObject(new { code = 200, msg = "I just to tell you, the connection is different from http, i still alive and could send message to you." }));
                    });
                }
            }
            else
            {
                Send(JsonConvert.SerializeObject(new { code = 400, msg = "request is not a json string." }));
            }
        }

        protected override void OnClose(CloseEventArgs e)
        {
            Console.WriteLine("Connection Closed");
            base.OnClose(e);
        }

        protected override void OnError(ErrorEventArgs e)
        {
            Console.WriteLine("Error: " + e.Message);
            base.OnError(e);
        }

        private static bool TestJson(string json)
        {
            try
            {
                JToken.Parse(json);
                return true;
            }
            catch (JsonReaderException ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }
    }
}

上面这一段代码中,重点在于OnMessage方法,这个方法就是处理消息的主要流程。websocket

在Main函数中,咱们加入下面的代码。6690是此次Demo使用的端口号,第二行AddWebSocketService添加了一行路由,使得链接到ws://localhost:6690/add能够导向咱们预约义好的App类中的处理逻辑。网络

using System;
using WebSocketSharp.Server;

namespace WebSocketDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var wssv = new WebSocketServer(6690);
            wssv.AddWebSocketService<Add>("/add");
            wssv.Start();
            Console.WriteLine("Server starting, press any key to terminate the server.");
            Console.ReadKey(true);
            wssv.Stop();
        }
    }
}

客户端代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>WebSocket DEMO</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      ul,
      li {
        padding: 0;
        margin: 0;
        list-style: none;
      }
    </style>
  </head>
  <body>
    <div>
      a:<input type="text" id="inpA" /> b:<input type="text" id="inpB" />
      <button type="button" id="btnSub">submit</button>
    </div>
    <ul id="outCnt"></ul>
    <script>
      let wsc;
      var echo = function(text) {
        var echoone = function(text) {
          var dom = document.createElement("li");
          var t = document.createTextNode(text);
          dom.appendChild(t);
          var cnt = document.getElementById("outCnt");
          cnt.appendChild(dom);
        };
        if (Array.isArray(text)) {
          text.map(function(t) {
            echoone(t);
          });
        } else {
          echoone(text);
        }
      };
      (function() {
        if ("WebSocket" in window) {
          // init the websocket client
          wsc = new WebSocket("ws://localhost:6690/add");
          wsc.onopen = function() {
            echo("connected");
          };
          wsc.onclose = function() {
            echo("closed");
          };
          wsc.onmessage = function(e) {
            var data = JSON.parse(e.data);
            echo(data.msg || e.data);
            console.log(data.msg || e.data);
          };

          // define click event for submit button
          document.getElementById("btnSub").addEventListener('click', function() {
            var a = parseInt(document.getElementById("inpA").value);
            var b = parseInt(document.getElementById("inpB").value);
            if (wsc.readyState == 1) {
              wsc.send(JSON.stringify({ a: a, b: b }));
            } else {
              echo("service is not available");
            }
          });
        }
      })();
    </script>
  </body>
</html>

当建立WebSocket对象的时候,会自动进行链接,这个对象能够用onopen,onclose,onmessage分别处理事件。主要通信的流程也是在onmessage中进行处理。app

相关文章
相关标签/搜索