近日项目有个windows服务需要用网络通讯与各端通讯,看了他代码后觉得用原生的方式写代码量有点多,而且需要自己轮询之类的,感觉用着比较奇怪。就从nuget上找了个websocket服务端与客户端包,初步使用下来感觉还不错,原先一直是在用fleckwebsocket-shrap这两个库的,后面作者不怎么更新了,好像只支持.netframework不支持.netcore;就想着搞几个其他c# websocket通信库用用看。

像这类开源websocket库也挺多的,有fleckwebsocket.clientwebsocket-sharp之所以单独把WatsonWebsocket 拿出来说,是因为它相对较新,而且.netframework和.netcore都支持。本文例子只做了webcosket服务端与客户端简单通信,文件收发没实现,不过也简单,在注释处填上代码就行了;以下是websocket客户端与服务的代码实例。本文例子地址:点此下载

服务端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WsServer
{
    public partial class FrmServer : Form
    {
        public FrmServer()
        {
            InitializeComponent();
        }

        //ws服务端对象
        private WatsonWebsocket.WatsonWsServer server;
        //在线客户端列表
        private List<string> clientList = new List<string>();
        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化ws服务
            server = new WatsonWebsocket.WatsonWsServer("*", 8080);
            //消息接收事件
            server.MessageReceived += OnMessageReceived;
            //客户端连接事件
            server.ClientConnected += OnClientConnected;
            //客户端断开连接事件
            server.ClientDisconnected += OnClientDisconnected;
            //开启监听
            server.Start();
        }

        private void OnClientDisconnected(object sender, WatsonWebsocket.ClientDisconnectedEventArgs e)
        {
            if (clientList.Contains(e.IpPort))
            {
                clientList.Remove(e.IpPort);
            }
            ShowMsg(e.IpPort, "我下线啦");
            ChangClient();

        }

        private void OnClientConnected(object sender, WatsonWebsocket.ClientConnectedEventArgs e)
        {
            if (!clientList.Contains(e.IpPort))
            {
                clientList.Add(e.IpPort);
            }
            ShowMsg(e.IpPort, "我上线啦");
            ChangClient();
        }

        private void OnMessageReceived(object sender, WatsonWebsocket.MessageReceivedEventArgs e)
        {
            switch (e.MessageType)
            {
                //文本消息
                case System.Net.WebSockets.WebSocketMessageType.Text:
                    ShowMsg(Encoding.UTF8.GetString(e.Data), e.IpPort);
                    break;
                //文件消息
                case System.Net.WebSockets.WebSocketMessageType.Binary:
                    break;
            }
        }

        private void ShowMsg(string text, string ip)
        {
            this.BeginInvoke((Action)delegate
            {
                richLog.Text += $"{ip}-{text}\r\n";
            });
        }
        private void ChangClient()
        {
            this.BeginInvoke((Action)delegate
            {
                cbo_client.DataSource = clientList;
            });
        }


        private void btn_send_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cbo_client.Text) && !string.IsNullOrEmpty(txt_msg.Text))
            {
                server.SendAsync(cbo_client.Text, txt_msg.Text);
            }
        }
    }
}

客户端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WsClient
{
    public partial class FrmClient : Form
    {
        public FrmClient()
        {
            InitializeComponent();
        }

        private WatsonWebsocket.WatsonWsClient client;
        private void FrmClient_Load(object sender, EventArgs e)
        {
            //设置服务器连接参数
            client = new WatsonWebsocket.WatsonWsClient("127.0.0.1", 8080, false);
            //消息接收事件
            client.MessageReceived += OnMessageReceived;
            //与服务器连接成功事件
            client.ServerConnected += OnServerConnected;
            //与服务器断开连接事件
            client.ServerDisconnected += OnServerDisconnected;
            //尝试连接服务端
            client.Start();
        }

        private void OnServerDisconnected(object sender, EventArgs e)
        {
            ShowMsg("与服务器断开连接", "系统消息");
        }

        private void OnServerConnected(object sender, EventArgs e)
        {
            ShowMsg("与服务器连接成功", "系统消息");
        }

        private void OnMessageReceived(object sender, WatsonWebsocket.MessageReceivedEventArgs e)
        {
            switch (e.MessageType)
            {
                //文本消息
                case System.Net.WebSockets.WebSocketMessageType.Text:
                    ShowMsg(Encoding.UTF8.GetString(e.Data), e.IpPort);
                    break;
                //文件消息
                case System.Net.WebSockets.WebSocketMessageType.Binary:
                    break;
            }
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txt_msg.Text))
            {
                client.SendAsync(txt_msg.Text);
            }
        }
        private void ShowMsg(string text, string ip)
        {
            this.BeginInvoke((Action)delegate
            {
                richLog.Text += $"{ip}-{text}\r\n";
            });
        }
    }
}

websocket通讯.jpg

最后修改:2022 年 09 月 29 日
免责声明:本站为个人博客,博客所发布的一切修改补丁、注册机和注册信息及软件的文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途。否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。访问和下载本站内容,说明您已同意上述条款。