C# Winform使用wss加密websocket
1)先去腾讯申请域名的免费ssl证书,注意记住证书密码:https://cloud.tencent.com/product/ssl
2)下载Fleck.dll并添加引用:fleck.dll下载
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); }; }); } } }
加支付宝好友偷能量挖...
原创文章,转载请注明出处:C# Winform使用wss加密websocket