C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码) ...

海哥  金牌会员 | 2022-9-17 08:38:01 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 893|帖子 893|积分 2679

前言

最近想做一个Web版的即时聊天为后面开发的各项功能做辅助,就需要浏览器与服务器能够实时通讯。而WebSocket这种双向通信协议,就很合适用来实现这种需求。
本篇文章主要解决C#如何实现WebSocket服务端和Javascript客户端基于wss协议的安全通信问题。
本文代码已开源至Github:https://github.com/hxsfx/WebSocketServerTest
环境


  • 编程语言:C#
  • Websocket开源库:fleck
  • SSL域名证书:腾讯云IIS版本域名证书
最终效果


代码实现

前端

1、HTML
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <meta charset="utf-8" />
  5.     <title></title>
  6.     <link href="Content/index.css" rel="stylesheet" />
  7. </head>
  8. <body>
  9.    
  10.         
  11.         
  12.         
  13.             <textarea id="SendMsgContent"></textarea>
  14.             <button id="SendMsgButton">发送</button>
  15.         
  16.    
  17.    
  18. </body>
  19. </html>
复制代码
2、JavaScript
  1. window.onload = function () {
  2.     var TipElement = document.querySelector("#ChatContainer > div.tip");
  3.     var MsgListElement = document.querySelector("#ChatContainer > div.msgList");
  4.     var SendMsgContentElement = document.getElementById("SendMsgContent");
  5.     var SendMsgButton = document.getElementById("SendMsgButton");
  6.     window.wss = new WebSocket("wss://xxx.hxsfx.com:xxx");
  7.     //监听消息状态
  8.     wss.onmessage = function (e) {
  9.         var dataJson = JSON.parse(e.data);
  10.         loadData(dataJson.nickName, dataJson.msg, dataJson.date, dataJson.time, true);
  11.     }
  12.     //监听链接状态
  13.     wss.onopen = function () {
  14.         if (TipElement.className.indexOf("conn") < 0) {
  15.             TipElement.className = TipElement.className + " conn";
  16.         }
  17.         if (TipElement.className.indexOf("disConn") >= 0) {
  18.             TipElement.className = TipElement.className.replace("disConn", "");
  19.         }
  20.     }
  21.     //监听关闭状态
  22.     wss.onclose = function () {
  23.         if (TipElement.className.indexOf("conn") >= 0) {
  24.             TipElement.className = TipElement.className.replace("conn", "");
  25.         }
  26.         if (TipElement.className.indexOf("disConn") < 0) {
  27.             TipElement.className = TipElement.className + " disConn";
  28.         }
  29.     }
  30.     //监控输入框回车键(直接发送输入内容)
  31.     SendMsgContentElement.onkeydown = function () {
  32.         if (event.keyCode == 13 && SendMsgContentElement.value.trim() != "") {
  33.             if (SendMsgContentElement.value.trim() != "") {
  34.                 SendMsgButton.click();
  35.                 event.returnValue = false;
  36.             } else {
  37.                 SendMsgContentElement.value = "";
  38.             }
  39.         }
  40.     }
  41.     //发送按钮点击事件
  42.     SendMsgButton.onclick = function () {
  43.         var msgDataJson = {
  44.             msg: SendMsgContentElement.value,
  45.         };
  46.         SendMsgContentElement.value = "";
  47.         var today = new Date();
  48.         var date = today.getFullYear() + "年" + (today.getMonth() + 1) + "月" + today.getDate() + "日";
  49.         var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  50.         loadData("自己", msgDataJson.msg, date, time, false);
  51.         let msgDataJsonStr = JSON.stringify(msgDataJson);
  52.         wss.send(msgDataJsonStr);
  53.     }
  54.     //把数据加载到对话框中
  55.     function loadData(nickName, msg, date, time, isOther) {
  56.         let msgItemElement = document.createElement('div');
  57.         if (isOther) {
  58.             msgItemElement.className = "msgItem other";
  59.         } else {
  60.             msgItemElement.className = "msgItem self";
  61.         }
  62.         let chatHeadElement = document.createElement('div');
  63.         chatHeadElement.className = "chatHead";
  64.         chatHeadElement.innerHTML = "<svg viewBox="0 0 1024 1024"><path d="M956.696128 512.75827c0 245.270123-199.054545 444.137403-444.615287 444.137403-245.538229 0-444.522166-198.868303-444.522166-444.137403 0-188.264804 117.181863-349.108073 282.675034-413.747255 50.002834-20.171412 104.631012-31.311123 161.858388-31.311123 57.297984 0 111.87909 11.128455 161.928996 31.311123C839.504032 163.650197 956.696128 324.494489 956.696128 512.75827L956.696128 512.75827M341.214289 419.091984c0 74.846662 38.349423 139.64855 94.097098 171.367973 23.119557 13.155624 49.151443 20.742417 76.769454 20.742417 26.64894 0 51.773154-7.096628 74.286913-19.355837 57.06467-31.113625 96.650247-96.707552 96.650247-172.742273 0-105.867166-76.664054-192.039781-170.936137-192.039781C417.867086 227.053226 341.214289 313.226864 341.214289 419.091984L341.214289 419.091984M513.886977 928.114163c129.883139 0 245.746984-59.732429 321.688583-153.211451-8.971325-73.739445-80.824817-136.51314-182.517917-167.825286-38.407752 34.55091-87.478354 55.340399-140.989081 55.340399-54.698786 0-104.770182-21.907962-143.55144-57.96211-98.921987 28.234041-171.379229 85.823668-188.368158 154.831344C255.507278 861.657588 376.965537 928.114163 513.886977 928.114163L513.886977 928.114163M513.886977 928.114163 513.886977 928.114163z"></path></svg>";
  65.         let msgMainElement = document.createElement('div');
  66.         msgMainElement.className = "msgMain";
  67.         let nickNameElement = document.createElement('div');
  68.         nickNameElement.className = "nickName";
  69.         nickNameElement.innerText = nickName;
  70.         let msgElement = document.createElement('div');
  71.         msgElement.className = "msg";
  72.         msgElement.innerText = msg;
  73.         let timeElement = document.createElement('div');
  74.         timeElement.className = "time";
  75.         let time_date_Element = document.createElement('span');
  76.         time_date_Element.innerText = date;
  77.         let time_time_Element = document.createElement('span');
  78.         time_time_Element.innerText = time;
  79.         timeElement.append(time_date_Element);
  80.         timeElement.append(time_time_Element);
  81.         msgMainElement.append(nickNameElement);
  82.         msgMainElement.append(msgElement);
  83.         msgMainElement.append(timeElement);
  84.         msgItemElement.append(chatHeadElement);
  85.         msgItemElement.append(msgMainElement);
  86.         MsgListElement.append(msgItemElement);
  87.         MsgListElement.scrollTop = MsgListElement.scrollHeight - MsgListElement.clientHeight;
  88.     }
  89. }
复制代码
3、CSS
  1. * {
  2.   padding: 0;
  3.   margin: 0;
  4. }
  5. html,
  6. body {
  7.   font-size: 14px;
  8.   height: 100%;
  9. }
  10. body {
  11.   padding: 2%;
  12.   box-sizing: border-box;
  13.   background-color: #a3aebc;
  14. }
  15. #ChatContainer {
  16.   padding: 1% 25px 0 25px;
  17.   width: 80%;
  18.   max-width: 850px;
  19.   height: 100%;
  20.   background-color: #fefefe;
  21.   border-radius: 10px;
  22.   box-sizing: border-box;
  23.   margin: auto;
  24. }
  25. #ChatContainer .tip {
  26.   height: 30px;
  27.   line-height: 30px;
  28.   text-align: center;
  29.   align-items: center;
  30.   justify-content: center;
  31.   color: #999999;
  32. }
  33. #ChatContainer .tip:before {
  34.   content: "连接中";
  35. }
  36. #ChatContainer .tip.disConn {
  37.   color: red;
  38. }
  39. #ChatContainer .tip.disConn:before {
  40.   content: "× 连接已断开";
  41. }
  42. #ChatContainer .tip.conn {
  43.   color: green;
  44. }
  45. #ChatContainer .tip.conn:before {
  46.   content: "√ 已连接";
  47. }
  48. #ChatContainer .msgList {
  49.   display: flex;
  50.   flex-direction: column;
  51.   overflow-x: hidden;
  52.   overflow-y: auto;
  53.   height: calc(100% - 100px);
  54. }
  55. #ChatContainer .msgList .msgItem {
  56.   display: flex;
  57.   margin: 5px;
  58. }
  59. #ChatContainer .msgList .msgItem .chatHead {
  60.   height: 36px;
  61.   width: 36px;
  62.   background-color: #ffffff;
  63.   border-radius: 100%;
  64. }
  65. #ChatContainer .msgList .msgItem .msgMain {
  66.   margin: 0 5px;
  67.   display: flex;
  68.   flex-direction: column;
  69. }
  70. #ChatContainer .msgList .msgItem .msgMain .nickName {
  71.   color: #666666;
  72. }
  73. #ChatContainer .msgList .msgItem .msgMain .msg {
  74.   padding: 10px;
  75.   line-height: 30px;
  76.   color: #333333;
  77. }
  78. #ChatContainer .msgList .msgItem .msgMain .time {
  79.   color: #999999;
  80.   font-size: 9px;
  81. }
  82. #ChatContainer .msgList .msgItem .msgMain .time span:first-child {
  83.   margin-right: 3px;
  84. }
  85. #ChatContainer .msgList .self {
  86.   flex-direction: row-reverse;
  87. }
  88. #ChatContainer .msgList .self .nickName {
  89.   text-align: right;
  90. }
  91. #ChatContainer .msgList .self .msg {
  92.   border-radius: 10px 0 10px 10px;
  93.   background-color: #d6e5f6;
  94. }
  95. #ChatContainer .msgList .self .time {
  96.   text-align: right;
  97. }
  98. #ChatContainer .msgList .other .msg {
  99.   border-radius: 0 10px 10px 10px;
  100.   background-color: #e8eaed;
  101. }
  102. #ChatContainer .msgInput {
  103.   margin: 15px 0;
  104.   display: flex;
  105. }
  106. #ChatContainer .msgInput textarea {
  107.   font-size: 16px;
  108.   padding: 0 5px;
  109.   width: 80%;
  110.   box-sizing: border-box;
  111.   height: 40px;
  112.   line-height: 40px;
  113.   overflow: hidden;
  114.   color: #333333;
  115.   border-radius: 10px 0 0 10px;
  116.   border: none;
  117.   outline: none;
  118.   border: 1px solid #eee;
  119.   resize: none;
  120. }
  121. #ChatContainer .msgInput button {
  122.   width: 20%;
  123.   text-align: center;
  124.   height: 40px;
  125.   line-height: 40px;
  126.   color: #fefefe;
  127.   background-color: #2a6bf2;
  128.   border-radius: 0 10px 10px 0;
  129.   border: 1px solid #2a6bf2;
  130. }
复制代码
后端

创建控制台程序(通过cmd命令调用,可修改源码为直接运行使用),然后进入Gnet安装fleck,其中的主要代码如下(完整源码移步github获取):
  1. //组合监听地址
  2. var loaction = webSocketProtocol + "://" + ListenIP + ":" + ListenPort;
  3. var webSocketServer = new WebSocketServer(loaction);
  4. if (loaction.StartsWith("wss://"))
  5. {
  6.     webSocketServer.Certificate = new X509Certificate2(pfxFilePath, pfxPassword
  7.    , X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
  8.     );
  9.     webSocketServer.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
  10. }//当为安全链接时,将证书信息写入链接
  11. //开始侦听
  12. webSocketServer.Start(socket =>
  13. {
  14.     var socketConnectionInfo = socket.ConnectionInfo;
  15.     var clientId = socketConnectionInfo.ClientIpAddress + ":" + socketConnectionInfo.ClientPort;
  16.     socket.OnOpen = () =>
  17.     {
  18.         if (!ip_scoket_Dic.ContainsKey(clientId))
  19.         {
  20.             ip_scoket_Dic.Add(clientId, socket);
  21.         }
  22.         Console.WriteLine(CustomSend("服务端", $"[{clientId}]加入"));
  23.     };
  24.     socket.OnClose = () =>
  25.     {
  26.         if (ip_scoket_Dic.ContainsKey(clientId))
  27.         {
  28.             ip_scoket_Dic.Remove(clientId);
  29.         }
  30.         Console.WriteLine(CustomSend("服务端", $"[{clientId}]离开"));
  31.     };
  32.     socket.OnMessage = message =>
  33.     {
  34.         //将发送过来的json字符串进行解析
  35.         var msgModel = JsonConvert.DeserializeObject<MsgModel>(message);
  36.         Console.WriteLine(CustomSend(clientId, msgModel.msg, clientId));
  37.     };
  38. });
  39. //出错后进行重启
  40. webSocketServer.RestartAfterListenError = true;
  41. Console.WriteLine("【开始监听】" + loaction);
  42. //服务端发送消息给客户端
  43. do
  44. {
  45.     Console.WriteLine(CustomSend("服务端", Console.ReadLine()));
  46. } while (true);
复制代码
问题及解决方法

问题:WebSocket connection to 'wss://xxx.xxx.xxx.xxx:xxxx/' failed:
解决方法:要建立WSS安全通道,必须要先申请域名SSL证书,同时在防火墙中开放指定端口,以及前端WSS请求域名要跟SSL证书域名相同。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

海哥

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表