WebSocket——SuperWebSocket实现服务端和客户端
WebSocket——SuperWebSocket实现服务端和客户端具体实现如下:
注:本作者是基于vs2019 enterprise版本,所有项目均为.Net Framwork4.7版本(因为WebSocket需求是.Net Framwork4.0以上版本)
1、新建控制台项目ConsoleAppWebsocketServer-2,作为服务端,选择项目右键管理Nuget程序包,搜索 SuperWebSocket ,选择SuperWebSocketNETServer,点击右侧 安装
安装完成以后,项目会多出很多引用库,如下
,
项目的Program.cs内容如下:
using SuperWebSocket;
using System;
using System.Web;
namespace ConsoleAppWebsocketServer_client
{
class Program
{
public static WebSocketServer ws = null;
static void Main(string[] args)
{
Console.WriteLine("WebSocket服务");
ws = new WebSocketServer();
ws.NewSessionConnected += Ws_NewSessionConnected;
ws.NewMessageReceived += Ws_NewMessageReceived;
ws.SessionClosed += Ws_SessionClosed;
if (!ws.Setup("127.0.0.1", 1234))
{
Console.WriteLine("ChatWebSocket 设置WebSocket服务侦听地址失败");
return;
}
if (!ws.Start())
{
Console.WriteLine("ChatWebSocket 启动WebSocket服务侦听失败");
return;
}
Console.WriteLine("ChatWebSocket 启动服务成功");
Console.ReadKey();
ws.Stop();
}
public static void Ws_NewSessionConnected(WebSocketSession session)
{
Console.WriteLine("{0:HH:MM:ss} 与客户端:{1}创建新会话", DateTime.Now, GetSessionName(session));
var msg = string.Format("{0:HH:MM:ss} {1} 进入聊天室", DateTime.Now, GetSessionName(session));
SendToAll(session, msg);
}
private static void Ws_NewMessageReceived(WebSocketSession session, string value)
{
var msg = string.Format("{0:HH:MM:ss} {1}说: {2}", DateTime.Now, GetSessionName(session), value);
Console.WriteLine($"{msg}");
SendToAll(session, msg);
}
public static void Ws_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
Console.WriteLine("{0:HH:MM:ss} 与客户端:{1}的会话被关闭 原因:{2}", DateTime.Now, GetSessionName(session), value);
var msg = string.Format("{0:HH:MM:ss} {1} 离开聊天室", DateTime.Now, GetSessionName(session));
SendToAll(session, msg);
}
/// <summary>
/// 启动服务
/// </summary>
/// <returns></returns>
public static void Start()
{
if (!ws.Setup("127.0.0.1", 1234))
{
Console.WriteLine("ChatWebSocket 设置WebSocket服务侦听地址失败");
return;
}
if (!ws.Start())
{
Console.WriteLine("ChatWebSocket 启动WebSocket服务侦听失败");
return;
}
Console.WriteLine("ChatWebSocket 启动服务成功");
}
/// <summary>
/// 停止侦听服务
/// </summary>
public static void Stop()
{
if (ws != null)
{
ws.Stop();
}
}
public static string GetSessionName(WebSocketSession session)
{
return HttpUtility.UrlDecode(session.Path.TrimStart('/'));
}
public static void SendToAll(WebSocketSession session, string msg)
{
foreach (var sendSession in session.AppServer.GetAllSessions())
{
sendSession.Send(msg);
}
}
}
}
2、新建控制台项目ConsoleAppWebsocketClient-2,作为客户端,选择项目右键管理Nuget程序包,为了测试SuperWebSocket作为服务端的功能,本文客户端使用了WebSocket4Net,同样可以使用 SuperWebSocket ,选择WebSocket4Net,点击右侧 安装
安装完成之后,同样项目下会多一些引用库,如下:
项目的Program.cs内容如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleAppWebsocketClient
{
class Program
{
static WebSocket4Net.WebSocket webSocket4NetFaceValidate = null;
static void Main(string[] args)
{
Console.WriteLine("WebSocket客户端");
Thread.Sleep(TimeSpan.FromSeconds(8));
webSocket4NetFaceValidate = new WebSocket4Net.WebSocket("ws://127.0.0.1:1234");
webSocket4NetFaceValidate.Opened += WebSocket4NetFaceValidate_Opened;
webSocket4NetFaceValidate.MessageReceived += WebSocket4NetFaceValidate_MessageReceived; ;
webSocket4NetFaceValidate.Open();
WebSocketSendmessage();
Thread thread = new Thread(WebSocketSendmessage);
thread.IsBackground = true;
thread.Start();
Console.ReadKey();
}
public static void WebSocketSendmessage()
{
int s = 88;
while (true)
{
webSocket4NetFaceValidate.Send(s.ToString());
s++;
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));
}
Console.WriteLine($"begin#123456");
byte[] bytess = Encoding.Default.GetBytes($"begin#123456");
IList<ArraySegment<byte>> list = new List<ArraySegment<byte>>();
list.Add(new ArraySegment<byte>(bytess));
webSocket4NetFaceValidate.Send(list);
}
private static void WebSocket4NetFaceValidate_Opened(object sender, EventArgs e)
{
Console.WriteLine($"begin#123456");
byte[] bytess = Encoding.Default.GetBytes($"begin#123456");
IList<ArraySegment<byte>> list = new List<ArraySegment<byte>>();
list.Add(new ArraySegment<byte>(bytess));
webSocket4NetFaceValidate.Send(list);
}
private static void WebSocket4NetFaceValidate_MessageReceived(object sender, WebSocket4Net.MessageReceivedEventArgs e)
{
try
{
string returnMessage = e.Message;
if (string.IsNullOrEmpty(returnMessage))
{
return;
}
Console.WriteLine(returnMessage);
}
catch (Exception ex)
{
}
finally
{
}
}
}
}
3、测试
为了看到测试效果,本作者又使用了js来测试,添加html文件,命名websockettest.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>
到此位置所有的准备工作,都完成了,接下来运行项目
设置启动项目如下:
运行效果: