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