记录一波,C#实现服务端及客户端(HTML及C#演示)
C#WebSocket服务端采用Fleck库,直接NuGet程序包引用。(默认是长连接,不发心跳也不断开连接)
public partial class Main : Form
{
private Dictionary<String, IWebSocketConnection> allSockets;
public Main()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false; //指定不再捕获对错误线程的调用 非线程安全
InitWs();
}
private void InitWs()
{
FleckLog.Level = LogLevel.Debug;
allSockets = new Dictionary<String, IWebSocketConnection>();
var server = new WebSocketServer("ws://0.0.0.0:7777");
server.RestartAfterListenError = true;
server.Start(socket =>
{
socket.OnOpen = () =>
{
//获取客户端网页的url
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
allSockets.Add(clientUrl, socket);
BoxAddInfo(DateTime.Now.ToString() + "|服务器:与客户端:" + clientUrl + " 建立WebSock连接!\r\n");
};
socket.OnClose = () =>
{
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
BoxAddInfo(DateTime.Now.ToString() + "|服务器:与客户端:" + clientUrl + " 断开WebSock连接!\r\n");
allSockets.Remove(clientUrl);
};
socket.OnMessage = message =>
{
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
BoxAddInfo(DateTime.Now.ToString() + "|服务器:【收到】客户端:" + clientUrl + "的信息:" + message + "\r\n");
Thread parameterizedThread = new Thread(new ParameterizedThreadStart(DoWorkWithParam));
Dictionary<String, String> da = new Dictionary<String, String>();
da.Add("clientUrl", clientUrl);
da.Add("message", message);
parameterizedThread.IsBackground = true; //后台线程
parameterizedThread.Start(da);
};
});
}
public void DoWorkWithParam(object o)
{
Dictionary<string, string> dictionary = (Dictionary<string, string>)o;
string clientUrl = dictionary["clientUrl"];
string message = dictionary["message"];
Thread.Sleep(5000);
allSockets[clientUrl].Send("5秒------" + message);
}
private void BoxAddInfo(String massage)
{
textBox1.Text += massage;
}
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
//关闭与客户端的所有的连接
/*
foreach (var socket in allSockets.Values)
{
socket.Send("服务关闭!");
}
*/
foreach (var item in allSockets.Values)
{
if (item != null)
{
item.Close();
}
}
}
}
C#WebSocket客户端采用webSocket4Net库,直接NuGet程序包引用。代码中采用事件委托,当有结果返回时执行业务代码使用如下:
private WebSocketService webSocket;
webSocket = (Application.Current as App).webSocket;
webSocket.Alarm += new WebSocketService.AlarmEventHandler(WebSocket_Alarm);
private void WebSocket_Alarm(string sender){
//业务代码
}
public partial class WebSocketService
{
public delegate void AlarmEventHandler(string sender); //声明关于事件的委托,参数为要回传的数据类型
public event AlarmEventHandler Alarm; //声明事件
private WebSocket webSocket4Net = null;
public WebSocketService()
{
if (webSocket4Net == null)
{
webSocket4Net = new WebSocket("ws://192.168.110.110:7777");
webSocket4Net.Opened += WebSocket4Net_Opened;
webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
webSocket4Net.Open();
}
}
public void ClientSendMsgToServer(object message)
{
webSocket4Net.Send(message.ToString());
}
public void ClientReceiveMsgToServer(string message)
{
this.Alarm(message);
}
private void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
{
this.ClientReceiveMsgToServer(e.Message);
}
private void WebSocket4Net_Opened(object sender, EventArgs e)
{
//webSocket4Net.Send($"客户端准备发送数据!");
}
}
HTML中使用:
<!DOCTYPE html>
<html lang="cn" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebSocket测试</title>
<style>
.div1
{
height:88px;
width:173px;
border:1px solid blue;
margin:auto;
}
h4
{
margin:auto;
}
</style>
<script>
var webSocket = {};
//创建websockt
function CreateWebSocket() {
webSocket = new WebSocket("ws://127.0.0.1:7777/");
webSocket.onopen = WebSokectOnOpen;
webSocket.onmessage = WebSocketOnMessage;
webSocket.onclose = WebSocketOnClose;
};
//建立连接事件
function WebSokectOnOpen() {
alert("已经打开连接!");
};
//监听事件
function WebSocketOnMessage(event) {
//监听来自客户端的数据
alert(event.data);
document.getElementById("Text2").value = event.data;
};
function WebSocketOnClose() {
//监听来自客户端的数据
alert('和服务器断开连接');
};
//发送事件
function WebSocketSendMsg() {
//获取text中的值
var text = document.getElementById("Text1").value;
//发送到服务器
webSocket.send(text);
document.getElementById("Text2").value = "通信中";
};
</script>
</head>
<body onload="CreateWebSocket()">
<div class="div1">
<h4>WebSocket通信</h4>
<input type="text" id="Text1" />
<input type="button" onclick="WebSocketSendMsg()" value="发送数据" />
<input type="text" id="Text2" />
</div>
</body>
</html>