C#winform窗体程序如何实现WebSocket的wss通讯?
1)先去腾讯申请域名的免费ssl证书,注意记住证书密码: SSL证书_免费SSL证书-付费SSL证书_服务器证书 - 腾讯云 腾讯云为您提供SSL证书(服务器证书)的一站式服务,包括免费SSL证书、付费SSL证书的申请、管理及部署功能以及与顶级的数字证书授权(CA)机构和代理商合作,为您的网站、移动应用提供 HTTPS 解决方案…… https://cloud.tencent.com/product/ssl
2)下载Fleck.dll并添加引用: C# websocket fleck.dll下载_Asp.net_Web开发网 http://www.w3dev.cn/download/20210818/csharp-websocket-fleck-dll.aspx
3)运行下面的代码就可以用浏览器建立wss链接了。
有帮助麻烦点个采纳【本回答右上角】,谢谢~~有其他问题可以继续交流~
using System;
using System.Windows.Forms;
using Fleck;
using System.Security.Cryptography.X509Certificates;
using System.Collections.Generic;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
List<IWebSocketConnection> users;
WebSocketServer server;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
listBox1.Items.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "-启动WebSocket");
users = new List<IWebSocketConnection>();//存储所有连接的socket对象
server = new WebSocketServer("wss://0.0.0.0:19999");
server.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(@"D:\内部\reservation.w3dev.cn\cert\reservation.w3dev.cn.pfx", "证书密码"
, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
);
server.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
server.RestartAfterListenError = true;
server.Start(socket =>
{
socket.OnOpen = () =>
{//连接成功加入队列
users.Add(socket);
};
socket.OnClose = () =>
{//客户端关闭
users.Remove(socket);
};
socket.OnMessage = message =>
{
this.Invoke(new Action(()=> {
listBox1.Items.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "-" + message);
}) );
foreach (var item in users) item.Send("服务器端回发信息-" + message);
};
});
}
}
}