• websocket练习


    html代码

    <!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>

    服务端代码

    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 ConsoleServer
    {
       public 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;
                }
            }
        }
    }

    Program启动项代码

     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();

    注意引用 Newtonsoft.JSON和DSharpPlus.WebSocket.WebSocketSharp 

    package代码

      Install-Package DSharpPlus.WebSocket.WebSocketSharp 
    
      Install-Package Newtonsoft.JSON
    萌橙 你瞅啥?
  • 相关阅读:
    使用Chrome开发者工具研究JavaScript的垃圾回收机制
    Java JDK目录下的jmap和jhat工具的使用方式
    Java注解@Cacheable的工作原理
    使用Java JUnit框架里的@Rule注解的用法举例
    使用Java JUnit框架里的@SuiteClasses注解管理测试用例
    Java JUnit框架里@Category注解的工作原理
    使用SAP CRM mock框架进行单元测试的设计
    将ABAP透明表的定义(元数据)解析出来导入到剪切板(clipboard)里
    SAP ABAP Netweaver里的胖接口(fat interface)
    关于STM32的FLASH操作【转载】
  • 原文地址:https://www.cnblogs.com/daimaxuejia/p/10904261.html
Copyright © 2020-2023  润新知