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