属于转载文档: 原创链接忘了
1、引用程序包
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8dd82e49fb3d2a2504c594147df5dc66.png)
2、服务端代码
using SuperSocket.SocketBase;
using SuperSocket.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Sockets;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
WebSocketServer server = new WebSocketServer();
//添加事件
server.NewSessionConnected += Server_NewSessionConnected;//当有用户连接过来时发生
server.NewMessageReceived += Server_NewMessageReceived; //接收消息时发生
server.SessionClosed += Server_SessionClosed;//关闭连接时发生的 事件
try
{
server.Setup("10.0.0.18", 6545);//监听
server.Start();//开始
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
//用来保存用户
public static List<WebSocketSession> sessionList = new List<WebSocketSession>();
//关闭连接时
private static void Server_SessionClosed(WebSocketSession session, CloseReason value)
{
sessionList.Remove(session);
Console.WriteLine(session.RemoteEndPoint.ToString()+"已经失去连接");
}
//接收消息
private static void Server_NewMessageReceived(WebSocketSession session, string value)
{
Console.WriteLine(value);
session.Send(value);
}
//当有用户连接过来时
private static void Server_NewSessionConnected(WebSocketSession session)
{
sessionList.Add(session);
//提示那个ip地址连接进来了
Console.WriteLine("ip: "+session.RemoteEndPoint.ToString()+"已经连接……");
}
}
}
3、客户端
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<textarea id="textarea" style="height: 500px; width: 300px;"></textarea>
<input type="button" id="send" onclick="send()" value="发送">
<input type="text" id="message">
<script type="text/javascript">
//检查浏览器是否支持WebSocket
if (!window.WebSocket) {
console.log('您的浏览器不支持WebSocket,请选择其他的浏览器再尝试连接服务器');
}
var el = document.getElementById("textarea");
var wsClient = new WebSocket('ws://10.0.0.18:6545');
wsClient.open = function (e) {
el.value += "连接成功!\r\n";
}
wsClient.onclose = function (e) {
el.value += "连接断开!\r\n";
}
wsClient.onmessage = function (e) {
console.log(wsClient);
el.value += "接收消息:" + e.data + "\r\n";
}
wsClient.onerror = function (e) {
el.value += "连接失败!原因【" + e.data + "】\r\n";
}
function send() {
var oText = document.getElementById("message");
wsClient.send( oText.value);
}
</script>
</body>
</html>