C#中 websocket

2021-04-10 10:28

阅读:534

标签:ref   data   cti   server   ati   back   服务端   bug   script   

 

C#中中主要是用Fleck,通过NuGet搜索安装就行

C#代码,控制台中program:

using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ws
{
    class Program
    {
        static void Main(string[] args)
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List();
            var server = new WebSocketServer("ws://0.0.0.0:7181");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                };
            });


            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
    }
}

html中

DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
html>
head>
    title>websocket clienttitle>
    script type="text/javascript">
        var start = function () {
            var inc = document.getElementById(incomming);
            var wsImpl = window.WebSocket || window.MozWebSocket;
            var form = document.getElementById(sendForm);
            var input = document.getElementById(sendText);

            inc.innerHTML += "connecting to server ..
"; // 创建新的websocket新连接端口为7181 window.ws = new wsImpl(ws://192.168.40.185:7181/); // 当数据从服务器服务中心发送后,继续向下运行过程 ws.onmessage = function (evt) { inc.innerHTML += evt.data +
; }; // 当链接对象找到服务端成功对接后,提示正常打开 ws.onopen = function () { inc.innerHTML += .. connection open
; }; // 当链接对象未找找到服务端成功对接后,提示打开失败,别切单项关闭 ws.onclose = function () { inc.innerHTML += .. connection closed
; } form.addEventListener(submit, function (e) { e.preventDefault(); var val = input.value; ws.send(val); input.value = ""; }); } window.onload = start; script> head> body> form id="sendForm"> input id="sendText" placeholder="Text to send" /> form> pre id="incomming">pre> body> html>

使用效果:

技术分享图片

原文:https://www.cnblogs.com/sheseido/p/7047948.html

 

C#中 websocket

标签:ref   data   cti   server   ati   back   服务端   bug   script   

原文地址:https://www.cnblogs.com/Cein/p/9046828.html


评论


亲,登录后才可以留言!