(1). Web网页端代码
<html lang="en" 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:30000");
webSocket.onopen = WebSokectOnOpen;
webSocket.onmessage = WebSocketOnMessage;
webSocket.onclose = WebSocketOnClose;
};
//建立连接事件
function WebSokectOnOpen() {
alert("已经打开连接!");
webSocket.Send("WebSocketCreate Success!");
};
//监听事件
function WebSocketOnMessage(event) {
//监听来自客户端的数据
alert(event.data);
};
function WebSocketOnClose() {
//监听来自客户端的数据
alert('和服务器断开连接');
};
//发送事件
function WebSocketSendMsg() {
//获取text中的值
var text = document.getElementById("Text1").value;
//发送到服务器
webSocket.send(text);
};
</script>
</head>
<body οnlοad="CreateWebSocket()">
<div class="div1">
<h4>CSDN博客</h4>
<h4>By:LoveMiw</h4>
<input type="text" />
</div>
</body>
</html>
(2). 服务端C#代码
//上面是程序生成的using
using Fleck;
namespace WebSocketTest
{
class Program
{
static void Main(string[] args)
{
//客户端url以及其对应的Socket对象字典
IDictionary<string, IWebSocketConnection> dic_Sockets = new Dictionary<string, IWebSocketConnection>();
//创建
WebSocketServer server = new WebSocketServer("ws://0.0.0.0:30000");//监听所有的的地址
//出错后进行重启
server.RestartAfterListenError = true;
//开始监听
server.Start(socket =>
{
socket.OnOpen = () => //连接建立事件
{
//获取客户端网页的url
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
dic_Sockets.Add(clientUrl, socket);
Console.WriteLine(DateTime.Now.ToString() + "|服务器:和客户端网页:" + clientUrl + " 建立WebSock连接!");
};
socket.OnClose = () => //连接关闭事件
{
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
//如果存在这个客户端,那么对这个socket进行移除
if (dic_Sockets.ContainsKey(clientUrl))
{
//注:Fleck中有释放
//关闭对象连接
//if (dic_Sockets[clientUrl] != null)
//{
//dic_Sockets[clientUrl].Close();
//}
dic_Sockets.Remove(clientUrl);
}
Console.WriteLine(DateTime.Now.ToString() + "|服务器:和客户端网页:" + clientUrl + " 断开WebSock连接!");
};
socket.OnMessage = message => //接受客户端网页消息事件
{
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
Console.WriteLine(DateTime.Now.ToString() + "|服务器:【收到】来客户端网页:" + clientUrl + "的信息:\n" + message);
};
});
Console.ReadKey();
foreach (var item in dic_Sockets.Values)
{
if (item.IsAvailable == true)
{
item.Send("服务器消息:" + DateTime.Now.ToString());
}
}
Console.ReadKey();
//关闭与客户端的所有的连接
foreach (var item in dic_Sockets.Values)
{
if (item != null)
{
item.Close();
}
}
Console.ReadKey();
}
}
}
请发表评论