zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

websocket-sharp 实现websocket

2023-02-19 12:17:09 时间

第一步,使用VS创建一个应用程序

第二步,添加引用 websocket-sharp DLL文件,或者NuGet程序包中添加

第三部,创建Laputa 类

using WebSocketSharp;
using WebSocketSharp.Server;

namespace ConsoleApp1
{
    public class Laputa : WebSocketBehavior
    {
        protected override void OnMessage(MessageEventArgs e)
        {
            var msg = "I'm not available now.";
            if(e.Data == "BALUS")
            {
                msg = "I've been balused already...";
            }
            Send(msg);
        }
    }
}

第四步,Program下写上如下代码

using System;
using WebSocketSharp.Server;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var wssv = new WebSocketServer(4649);
            wssv.AddWebSocketService<Laputa>("/Laputa");

            wssv.Start();
            if (wssv.IsListening)
            {
                Console.WriteLine("Listening on port {0}, and providing WebSocket services:", wssv.Port);
                foreach (var path in wssv.WebSocketServices.Paths)
                    Console.WriteLine("- {0}", path);
            }

            Console.WriteLine("\nPress Enter key to stop the server...");
            Console.ReadLine();

            wssv.Stop();
        }
    }
}

第五步,前端调用代码

<html>
<head>
    <title>websocket client</title>
    <script type="text/javascript">
        var ws;
        function startWS() {
            ws = new WebSocket("ws://127.0.0.1:4649/Laputa");
            ws.onopen = function (msg) {
                console.log("Openened connection to websocket");
            };
            ws.onmessage = function (message) {
                console.log('receive message: ' + message.data);
            };
            ws.onerror = function (error) {
                console.log('Error: ' + error.name + error.number);
            };
            ws.onclose = function () {
                console.log("Close connection to websocket");
                startWS();
            };
        }

        function sendMessage() {
            console.log('Sending a message...');
            ws.send('BALUS');
        }

        window.onbeforeunload = function () {
            ws.onclose = function () { };  // 首先关闭 WebSocket
            ws.close()
        };

        startWS();
    </script>
</head>
<body>
    <button onclick="sendMessage()">测试</button>
</body>
</html>

 

 测试成功了。