SuperWebSocket implement server and client to achieve WebSocket4Net

SuperWebSocket implement server and client WebSocket4Net achieve concrete realization of the following:

SuperWebSocket implement server

Note: The author is based on vs2019 enterprise version, all items are .Net Framwork4.7 version (because demand is WebSocket .Net Framwork4.0 or later)

1, the new console project ConsoleAppWebsocketServer, as a server, select the right project management Nuget package search SuperWebSocket, select SuperWebSocketNETServer, click on the right side of the installation,

Wait for the installation to complete, after the installation is complete, the project will be a lot more reference library as follows 

 

Program.cs contents of the project are as follows:

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 ( "Press any key to end ...");
the 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>
/// broadcast synchronization messages to all push client
/// </ Summary>
/// <param name = "webSocketSession"> </ param>
/// <param name = "MSG "> </ param>
public static void SendToAll (webSocketSession webSocketSession, String MSG)
{
the foreach (var webSocketSession.AppServer.GetAllSessions in Item ())
{
Item.Send (MSG);
}
}
}
}

 

WebSocket4Net implementation of the client

 2, the new console project ConsoleAppWebsocketClient, as a client, select the right project management Nuget package, in order to test SuperWebSocket as a function of the server, this client uses WebSocket4Net , also can be used SuperWebSocket, the project selection WebSocket4Net, click on the right installation , wait for the installation to complete, after the installation is complete, the project will be more under the same reference libraries, as follows:

 

Program.cs contents of the project are as follows:

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,

运行效果:

 

Guess you like

Origin www.cnblogs.com/1175429393wljblog/p/11210910.html