前言 最近想做一個Web版的即時聊天為後面開發的各項功能做輔助,就需要瀏覽器與伺服器能夠實時通訊。而WebSocket這種雙向通信協議,就很合適用來實現這種需求。 本篇文章主要解決C#如何實現WebSocket服務端和Javascript客戶端基於wss協議的安全通信問題。 本文代碼已開源至Gith ...
前言
最近想做一個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>
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;
}
}
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;
}
後端
創建控制台程式(通過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);
問題及解決方法
問題:WebSocket connection to 'wss://xxx.xxx.xxx.xxx:xxxx/' failed:
解決方法:要建立WSS安全通道,必須要先申請功能變數名稱SSL證書,同時在防火牆中開放指定埠,以及前端WSS請求功能變數名稱要跟SSL證書功能變數名稱相同。
博客園-本文作者(好先生FX http://www.cnblogs.com/hxsfx)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。