侧边栏壁纸
  • 累计撰写 62 篇文章
  • 累计收到 17 条评论

websocket使用教程(WatsonWebsocket)

一缕清风
2021-02-04 / 0 评论 / 45 阅读 / 正在检测是否收录...

简介

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

0

评论 (0)

取消