.net core Fleck WebSocket使用笔记

@@.net core Fleck

 

socket帮助类

    using Fleck;
    using KOTL_EvidenceService.Model;
    using System;
    using System.Collections.Generic;

    namespace KOTL_EvidenceService.Util
    {
        public class ServerHelper
        {
            WebSocketServer server = null;
            SessionEntiy session = new SessionEntiy();
            public ServerHelper()
            {
                server = new WebSocketServer("ws://192.168.0.36:7010");//监听所有的的地址
                                                                       //出错后进行重启
                server.RestartAfterListenError = true;
            }

            public void Start()
            {
                //开始监听
                server.Start(socket =>
                {
                    socket.OnOpen = () => OnOpen(socket);
                    socket.OnClose = () => OnClose(socket);
                    socket.OnMessage = message => //接受客户端网页消息事件
                    {
                        string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                        Console.WriteLine(DateTime.Now.ToString() + "|服务器:【收到】来客户端网页:" + clientUrl + "的信息:\n" + message);
                    };
                });
            }

            public void OnOpen(IWebSocketConnection socket)
            {
                //获取客户端网页的url
                string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                Console.WriteLine(DateTime.Now.ToString() + "|服务器:和客户端网页:" + clientUrl + " 建立WebSock连接!");
            }

            //连接关闭事件
            public void OnClose(IWebSocketConnection socket)
            {
                string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                Console.WriteLine(DateTime.Now.ToString() + "|服务器:和客户端网页:" + clientUrl + " 断开WebSock连接!");
            }
        }
    }
    调用

    ServerHelper websocket = new ServerHelper();
    websocket.Start();

 

————————————————
版权声明:本文为CSDN博主「qq_40580931」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_40580931/article/details/120781798

posted @ 2023-08-11 17:51  dreamw  阅读(144)  评论(0编辑  收藏  举报