SuperWebSocket实现服务端和WebSocket4Net实现客户端
Posted 龙腾一族至尊龙骑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SuperWebSocket实现服务端和WebSocket4Net实现客户端相关的知识,希望对你有一定的参考价值。
SuperWebSocket实现服务端和WebSocket4Net实现客户端具体实现如下:
SuperWebSocket实现服务端
注:本作者是基于vs2019 enterprise版本,所有项目均为.Net Framwork4.7版本(因为WebSocket需求是.Net Framwork4.0以上版本)
1、新建控制台项目ConsoleAppWebsocketServer,作为服务端,选择项目右键管理Nuget程序包,搜索 SuperWebSocket ,选择SuperWebSocketNETServer,点击右侧 安装,
等待安装完成,安装完成以后,项目会多出很多引用库,如下
,
项目的Program.cs内容如下:
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace ConsoleAppWebsocketServer
class Program
static void Main(string[] args)
Console.WriteLine("服务端");
WebSocketServer webSocketServer = new WebSocketServer();
webSocketServer.NewSessionConnected += WebSocketServer_NewSessionConnected;
webSocketServer.NewMessageReceived += WebSocketServer_NewMessageReceived;
webSocketServer.SessionClosed += WebSocketServer_SessionClosed;
if (!webSocketServer.Setup("127.0.0.1", 1234))
Console.WriteLine("设置服务监听失败!");
if (!webSocketServer.Start())
Console.WriteLine("启动服务监听失败!");
Console.WriteLine("启动服务监听成功!");
Console.WriteLine("按任意键结束。。。");
Console.ReadKey();
webSocketServer.Dispose();
private static void WebSocketServer_NewSessionConnected(WebSocketSession session)
string msg = $"DateTime.Now.ToString("HH:mm:ss") 客户端:GetwebSocketSessionName(session) 加入";
Console.WriteLine($"msg");
SendToAll(session, msg);
private static void WebSocketServer_NewMessageReceived(WebSocketSession session, string value)
string msg = $"DateTime.Now.ToString("HH:mm:ss") 服务端收到客户端:GetwebSocketSessionName(session)发送数据:value";
Console.WriteLine($"msg");
SendToAll(session, value);
private static void WebSocketServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
string msg = $"DateTime.Now.ToString("HH:mm:ss") 客户端:GetwebSocketSessionName(session)关闭,原因:value";
Console.WriteLine($"msg");
SendToAll(session, msg);
/// <summary>
/// 获取webSocketSession的名称
/// </summary>
/// <param name="webSocketSession"></param>
public static string GetwebSocketSessionName(WebSocketSession webSocketSession)
return HttpUtility.UrlDecode(webSocketSession.SessionID);
/// <summary>
/// 广播,同步推送消息给所有的客户端
/// </summary>
/// <param name="webSocketSession"></param>
/// <param name="msg"></param>
public static void SendToAll(WebSocketSession webSocketSession, string msg)
foreach (var item in webSocketSession.AppServer.GetAllSessions())
item.Send(msg);
WebSocket4Net实现客户端
2、新建控制台项目ConsoleAppWebsocketClient,作为客户端,选择项目右键管理Nuget程序包,为了测试SuperWebSocket作为服务端的功能,本文客户端使用了WebSocket4Net,同样也可以使用 SuperWebSocket ,本项目选择WebSocket4Net,点击右侧 安装,等待安装完成,安装完成之后,同样项目下会多一些引用库,如下:
项目的Program.cs内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocket4Net;
using System.Threading;
namespace ConsoleAppWebsocketClient
class Program
public static WebSocket webSocket4Net = null;
static void Main(string[] args)
Console.WriteLine("客户端");
webSocket4Net = new WebSocket("ws://127.0.0.1:1234");
webSocket4Net.Opened += WebSocket4Net_Opened;
webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
webSocket4Net.Open();
Console.WriteLine("客户端连接成功!");
Thread thread = new Thread(ClientSendMsgToServer);
thread.IsBackground = true;
thread.Start();
Console.WriteLine("按任意键结束。。。");
Console.ReadKey();
webSocket4Net.Dispose();
public static void ClientSendMsgToServer()
int i = 88;
while (true)
//Console.WriteLine($"客户端发送数据i++");
webSocket4Net.Send($"i++");
Thread.Sleep(TimeSpan.FromSeconds(5));
private static void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
Console.WriteLine($"服务端回复数据:e.Message!");
private static void WebSocket4Net_Opened(object sender, EventArgs e)
webSocket4Net.Send($"客户端准备发送数据!");
3、测试
为了更好的看到测试效果,又多使用了js客户端来测试,添加html文件,命名websockettest.html,内容如下:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="https://www.baidu.com" />
<title>websocket test</title>
<script>
var socket;
function Connect()
try
socket=new WebSocket(ws://127.0.0.1:1234);
catch(e)
alert(error);
return;
socket.onopen = sOpen;
socket.onerror = sError;
socket.onmessage= sMessage;
socket.onclose= sClose;
function sOpen()
alert(connect success!);
function sError(e)
alert("error " + e);
function sMessage(msg)
document.getElementById("msgrecv").value = msg.data;
function sClose(e)
alert("connect closed:" + e.code);
function Send()
socket.send(document.getElementById("msg").value);
function Close()
socket.close();
</script>
</head>
<body>
<input id="msg" type="text" size = "200" >
<input id="msgrecv" type="text" size = "200">
<button id="connect" onclick="Connect();">Connect</button>
<button id="send" onclick="Send();">Send</button>
<button id="close" onclick="Close();">Close</button>
</body>
</html>
4、运行结果
到此位置所有的准备工作都完成了,一个服务端ConsoleAppWebsocketServer,两个客户端(ConsoleAppWebsocketClient,websockettest.html),那么接下来运行项目
解决方案 右键,属性,设置启动项目如下:
启动服务端ConsoleAppWebsocketServer,客户端ConsoleAppWebsocketClient之后,再去手动点击websockettest.html,
运行效果:
龙腾一族至尊龙骑
以上是关于SuperWebSocket实现服务端和WebSocket4Net实现客户端的主要内容,如果未能解决你的问题,请参考以下文章
在 asp.net 中是不是默认提供 superwebsocket?