当前位置:   article > 正文

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

fleck wss

前言

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

环境

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

最终效果

在这里插入图片描述

代码实现

前端

1、HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link href="Content/index.css" rel="stylesheet" />
</head>
<body>
    <div id="ChatContainer">
        <div class="tip "></div>
        <div class="msgList"></div>
        <div class="msgInput">
            <textarea id="SendMsgContent"></textarea>
            <button id="SendMsgButton">发送</button>
        </div>
    </div>
    <script src="Scripts/index.js"></script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

2、JavaScript

window.onload = function () {
    var TipElement = document.querySelector("#ChatContainer > div.tip");
    var MsgListElement = document.querySelector("#ChatContainer > div.msgList");
    var SendMsgContentElement = document.getElementById("SendMsgContent");
    var SendMsgButton = document.getElementById("SendMsgButton");
    window.wss = new WebSocket("wss://xxx.hxsfx.com:xxx");
    //监听消息状态
    wss.onmessage = function (e) {
        var dataJson = JSON.parse(e.data);
        loadData(dataJson.nickName, dataJson.msg, dataJson.date, dataJson.time, true);
    }
    //监听链接状态
    wss.onopen = function () {
        if (TipElement.className.indexOf("conn") < 0) {
            TipElement.className = TipElement.className + " conn";
        }
        if (TipElement.className.indexOf("disConn") >= 0) {
            TipElement.className = TipElement.className.replace("disConn", "");
        }
    }
    //监听关闭状态
    wss.onclose = function () {
        if (TipElement.className.indexOf("conn") >= 0) {
            TipElement.className = TipElement.className.replace("conn", "");
        }
        if (TipElement.className.indexOf("disConn") < 0) {
            TipElement.className = TipElement.className + " disConn";
        }
    }
    //监控输入框回车键(直接发送输入内容)
    SendMsgContentElement.onkeydown = function () {
        if (event.keyCode == 13 && SendMsgContentElement.value.trim() != "") {
            if (SendMsgContentElement.value.trim() != "") {
                SendMsgButton.click();
                event.returnValue = false;
            } else {
                SendMsgContentElement.value = "";
            }
        }
    }
    //发送按钮点击事件
    SendMsgButton.onclick = function () {
        var msgDataJson = {
            msg: SendMsgContentElement.value,
        };
        SendMsgContentElement.value = "";
        var today = new Date();
        var date = today.getFullYear() + "年" + (today.getMonth() + 1) + "月" + today.getDate() + "日";
        var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
        loadData("自己", msgDataJson.msg, date, time, false);
        let msgDataJsonStr = JSON.stringify(msgDataJson);
        wss.send(msgDataJsonStr);
    }
    //把数据加载到对话框中
    function loadData(nickName, msg, date, time, isOther) {
        let msgItemElement = document.createElement('div');
        if (isOther) {
            msgItemElement.className = "msgItem other";
        } else {
            msgItemElement.className = "msgItem self";
        }
        let chatHeadElement = document.createElement('div');
        chatHeadElement.className = "chatHead";
        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>";
        let msgMainElement = document.createElement('div');
        msgMainElement.className = "msgMain";
        let nickNameElement = document.createElement('div');
        nickNameElement.className = "nickName";
        nickNameElement.innerText = nickName;
        let msgElement = document.createElement('div');
        msgElement.className = "msg";
        msgElement.innerText = msg;
        let timeElement = document.createElement('div');
        timeElement.className = "time";
        let time_date_Element = document.createElement('span');
        time_date_Element.innerText = date;
        let time_time_Element = document.createElement('span');
        time_time_Element.innerText = time;
        timeElement.append(time_date_Element);
        timeElement.append(time_time_Element);
        msgMainElement.append(nickNameElement);
        msgMainElement.append(msgElement);
        msgMainElement.append(timeElement);
        msgItemElement.append(chatHeadElement);
        msgItemElement.append(msgMainElement);
        MsgListElement.append(msgItemElement);
        MsgListElement.scrollTop = MsgListElement.scrollHeight - MsgListElement.clientHeight;
    }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89

3、CSS

* {
  padding: 0;
  margin: 0;
}
html,
body {
  font-size: 14px;
  height: 100%;
}
body {
  padding: 2%;
  box-sizing: border-box;
  background-color: #a3aebc;
}
#ChatContainer {
  padding: 1% 25px 0 25px;
  width: 80%;
  max-width: 850px;
  height: 100%;
  background-color: #fefefe;
  border-radius: 10px;
  box-sizing: border-box;
  margin: auto;
}
#ChatContainer .tip {
  height: 30px;
  line-height: 30px;
  text-align: center;
  align-items: center;
  justify-content: center;
  color: #999999;
}
#ChatContainer .tip:before {
  content: "连接中";
}
#ChatContainer .tip.disConn {
  color: red;
}
#ChatContainer .tip.disConn:before {
  content: "× 连接已断开";
}
#ChatContainer .tip.conn {
  color: green;
}
#ChatContainer .tip.conn:before {
  content: "√ 已连接";
}
#ChatContainer .msgList {
  display: flex;
  flex-direction: column;
  overflow-x: hidden;
  overflow-y: auto;
  height: calc(100% - 100px);
}
#ChatContainer .msgList .msgItem {
  display: flex;
  margin: 5px;
}
#ChatContainer .msgList .msgItem .chatHead {
  height: 36px;
  width: 36px;
  background-color: #ffffff;
  border-radius: 100%;
}
#ChatContainer .msgList .msgItem .msgMain {
  margin: 0 5px;
  display: flex;
  flex-direction: column;
}
#ChatContainer .msgList .msgItem .msgMain .nickName {
  color: #666666;
}
#ChatContainer .msgList .msgItem .msgMain .msg {
  padding: 10px;
  line-height: 30px;
  color: #333333;
}
#ChatContainer .msgList .msgItem .msgMain .time {
  color: #999999;
  font-size: 9px;
}
#ChatContainer .msgList .msgItem .msgMain .time span:first-child {
  margin-right: 3px;
}
#ChatContainer .msgList .self {
  flex-direction: row-reverse;
}
#ChatContainer .msgList .self .nickName {
  text-align: right;
}
#ChatContainer .msgList .self .msg {
  border-radius: 10px 0 10px 10px;
  background-color: #d6e5f6;
}
#ChatContainer .msgList .self .time {
  text-align: right;
}
#ChatContainer .msgList .other .msg {
  border-radius: 0 10px 10px 10px;
  background-color: #e8eaed;
}
#ChatContainer .msgInput {
  margin: 15px 0;
  display: flex;
}
#ChatContainer .msgInput textarea {
  font-size: 16px;
  padding: 0 5px;
  width: 80%;
  box-sizing: border-box;
  height: 40px;
  line-height: 40px;
  overflow: hidden;
  color: #333333;
  border-radius: 10px 0 0 10px;
  border: none;
  outline: none;
  border: 1px solid #eee;
  resize: none;
}
#ChatContainer .msgInput button {
  width: 20%;
  text-align: center;
  height: 40px;
  line-height: 40px;
  color: #fefefe;
  background-color: #2a6bf2;
  border-radius: 0 10px 10px 0;
  border: 1px solid #2a6bf2;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131

后端

创建控制台程序(通过cmd命令调用,可修改源码为直接运行使用),然后进入Gnet安装fleck,其中的主要代码如下(完整源码移步github获取):

//组合监听地址
var loaction = webSocketProtocol + "://" + ListenIP + ":" + ListenPort;
var webSocketServer = new WebSocketServer(loaction);
if (loaction.StartsWith("wss://"))
{
    webSocketServer.Certificate = new X509Certificate2(pfxFilePath, pfxPassword
   , X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
    );
    webSocketServer.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
}//当为安全链接时,将证书信息写入链接
//开始侦听
webSocketServer.Start(socket =>
{
    var socketConnectionInfo = socket.ConnectionInfo;
    var clientId = socketConnectionInfo.ClientIpAddress + ":" + socketConnectionInfo.ClientPort;
    socket.OnOpen = () =>
    {
        if (!ip_scoket_Dic.ContainsKey(clientId))
        {
            ip_scoket_Dic.Add(clientId, socket);
        }
        Console.WriteLine(CustomSend("服务端", $"[{clientId}]加入"));
    };
    socket.OnClose = () =>
    {
        if (ip_scoket_Dic.ContainsKey(clientId))
        {
            ip_scoket_Dic.Remove(clientId);
        }
        Console.WriteLine(CustomSend("服务端", $"[{clientId}]离开"));
    };
    socket.OnMessage = message =>
    {
        //将发送过来的json字符串进行解析
        var msgModel = JsonConvert.DeserializeObject<MsgModel>(message);
        Console.WriteLine(CustomSend(clientId, msgModel.msg, clientId));
    };
});
//出错后进行重启
webSocketServer.RestartAfterListenError = true;
Console.WriteLine("【开始监听】" + loaction);
//服务端发送消息给客户端
do
{
    Console.WriteLine(CustomSend("服务端", Console.ReadLine()));
} while (true);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

问题及解决方法

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/164623
推荐阅读
相关标签
  

闽ICP备14008679号