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

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

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

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

这个DEMO主要完成的工作是:

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

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

  • HTTP是由客户端发起请求,服务器对请求进行处理之后做出相应的过程。
  • WebSocket跟Socket一样,一旦建立连接,服务器可以通过WebSocket主动向客户端发送数据。

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

准备姿势

新建工程

首先需要准备两个工程:

  • 一个是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方法,这个方法就是处理消息的主要流程。

在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中进行处理。

也可以看看 GoEasy文库 的其他资料

发表评论

邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据