C#写一个WebService服务器

首先在NuGet中下载Fleck动态库

创建一个WebSocketHelper类

csharp 复制代码
public class WebSocketHelper
{
    //客户端url以及其对应的Socket对象字典
    IDictionary<string, IWebSocketConnection> dic_Sockets = new Dictionary<string, IWebSocketConnection>();
    //创建一个 websocket ,0.0.0.0 为监听所有的的地址
    WebSocketServer server = new WebSocketServer("ws://127.0.0.1:50000");

    //打开连接委托
    public delegate void _OnOpen(string ip);
    public event _OnOpen OnOpen;
    //关闭连接委托
    public delegate void _OnClose(string ip);
    public event _OnClose OnClose;
    //当收到消息
    public delegate void _OnMessage(string ip, string msg);
    public event _OnMessage OnMessage;

    /// <summary>
    /// 初始化
    /// </summary>
    private void Init()
    {
        //出错后进行重启
        server.RestartAfterListenError = true;

        //开始监听
        server.Start(socket =>
        {
            //连接建立事件
            socket.OnOpen = () =>
            {
                //获取客户端网页的url
                string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                dic_Sockets.Add(clientUrl, socket);
                if (OnOpen != null) OnOpen(clientUrl);
                Console.WriteLine(DateTime.Now.ToString() + " | 服务器:和客户端:" + clientUrl + " 建立WebSock连接!");
            };

            //连接关闭事件
            socket.OnClose = () =>
            {
                string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                //如果存在这个客户端,那么对这个socket进行移除
                if (dic_Sockets.ContainsKey(clientUrl))
                {
                    dic_Sockets.Remove(clientUrl);
                    if (OnClose != null) OnClose(clientUrl);
                }
                Console.WriteLine(DateTime.Now.ToString() + " | 服务器:和客户端:" + clientUrl + " 断开WebSock连接!");
            };

            //接受客户端网页消息事件
            socket.OnMessage = message =>
            {
                string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                Receive(clientUrl, message);
                if (OnMessage != null)
                    OnMessage(clientUrl, message);
            };
        });
    }

    /// <summary>
    /// 向客户端发送消息
    /// </summary>
    /// <param name="webSocketConnection">客户端实例</param>
    /// <param name="message">消息内容</param>
    public void Send(string clientUrl, string message)
    {
        IWebSocketConnection webSocketConnection = GetUserSocketInstance(clientUrl);
        if (webSocketConnection != null)
        {
            if (webSocketConnection.IsAvailable)
            {
                webSocketConnection.Send(message);
            }
        }
    }

    /// <summary>
    /// 接收消息
    /// </summary>
    /// <param name="clientUrl"></param>
    /// <param name="message"></param>
    private void Receive(string clientUrl, string message)
    {
        Console.WriteLine(DateTime.Now.ToString() + " | 服务器:【收到】来客户端:" + clientUrl + "的信息:\n" + message);
    }

    /// <summary>
    /// 获取用户实例
    /// </summary>
    /// <param name="clientUrl">用户的地址</param>
    public IWebSocketConnection GetUserSocketInstance(string clientUrl)
    {
        if (dic_Sockets.ContainsKey(clientUrl))
            return dic_Sockets[clientUrl];
        else
            return null;
    }

    /// <summary>
    /// 关闭某一个用户的连接
    /// </summary>
    /// <param name="clientUrl"></param>
    public void CloseUserConnect(string clientUrl)
    {
        IWebSocketConnection webSocketConnection = GetUserSocketInstance(clientUrl);
        if (webSocketConnection != null)
            webSocketConnection.Close();
    }

    /// <summary>
    /// 关闭与客户端的所有的连接
    /// </summary>
    public void CloseAllConnect()
    {
        foreach (var item in dic_Sockets.Values)
        {
            if (item != null)
            {
                item.Close();
            }
        }
    }

    public WebSocketHelper()
    {
        Init();
    }
}

使用方法:

csharp 复制代码
internal class Program
{
    private static List<string> IPList = new List<string>();
    private static WebSocketHelper webSocketHelpers = new WebSocketHelper();

    static void Main(string[] args)
    {
        webSocketHelpers.OnOpen += WebSocketHelper_OnOpen;
        webSocketHelpers.OnClose += WebSocketHelper_OnClose;
        webSocketHelpers.OnMessage += WebSocketHelper_OnMessage;

        Console.ReadLine();
    }


    #region WebSocket回调

    //当收到消息
    private static void WebSocketHelper_OnMessage(string ip, string msg)
    {
        for (int i = 0; i < IPList.Count; i++)
        {
            if (IPList[i] != ip)
            {
                webSocketHelpers.Send(IPList[i], msg);
            }
        }
    }

    //当客户端断开连接
    private static void WebSocketHelper_OnClose(string ip)
    {
        if (IPList.Contains(ip))
        {
            IPList.Remove(ip);
        }
    }

    //当客户端连接上服务器
    private static void WebSocketHelper_OnOpen(string ip)
    {
        if (!IPList.Contains(ip))
        {
            IPList.Add(ip);
        }
    }

    #endregion


    //转发所有客户端
    private static void Relay(string content)
    {
        if (IPList.Count == 0) return;

        for (int i = 0; i < IPList.Count; i++)
        {
            webSocketHelpers.Send(IPList[i], content);
        }
    }
}
相关推荐
试行37 分钟前
C#System.Runtime.InteropServices.ExternalException (0x80004005): GDI+ 中发生一般性错误。
c#
每日出拳老爷子4 小时前
[C#] 使用TextBox换行失败的原因与解决方案:换用RichTextBox的实战经验
开发语言·c#
程序猿多布12 小时前
C# 值拷贝、引用拷贝、浅拷贝、深拷贝
c#
阿蒙Amon14 小时前
C#随机数生成全面详解:从基础到高级应用
服务器·网络·c#
开开心心_Every14 小时前
便捷的电脑自动关机辅助工具
开发语言·人工智能·pdf·c#·电脑·音视频·sublime text
我要打打代码16 小时前
C#Winform窗体显示模糊的问题
c#
阿蒙Amon16 小时前
C#正则表达式全面详解:从基础到高级应用
开发语言·正则表达式·c#
水果里面有苹果19 小时前
19-C#静态方法与静态类
java·开发语言·c#
吃着火锅x唱着歌19 小时前
LeetCode 3306.元音辅音字符串计数2
算法·leetcode·c#
格林威1 天前
Baumer工业相机堡盟工业相机如何通过DeepOCR模型识别判断数值和字符串的范围和相似度(C#)
开发语言·人工智能·python·数码相机·计算机视觉·c#·视觉检测