• 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
    萌橙 你瞅啥?
  • 相关阅读:
    Linux运维工作总结教训
    java-GC
    java设计模式-原形模式
    java-桥接模式
    java-装饰者模式
    java-正则表达式
    java设计模式-建造者模式
    Python 条件与循环
    Python 集合、字典、运算符
    Python 字符串拼接、格式化输出、深浅复制
  • 原文地址:https://www.cnblogs.com/daimaxuejia/p/10904261.html
Copyright © 2020-2023  润新知