博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WebSocket——SuperWebSocket实现服务端和客户端
阅读量:5111 次
发布时间:2019-06-13

本文共 5666 字,大约阅读时间需要 18 分钟。

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" οnclick="Connect();">Connect</button>
<button id="send" οnclick="Send();">Send</button>
<button id="close" οnclick="Close();">Close</button>

</body>

</html>

 

到此位置所有的准备工作,都完成了,接下来运行项目

 设置启动项目如下:

 

运行效果:

 

转载于:https://www.cnblogs.com/1175429393wljblog/p/11209204.html

你可能感兴趣的文章
VC++编程 两类典型的 LNK2001错误分析及解决方法
查看>>
对于redis框架的理解(三)
查看>>
C语言模块化编译介绍
查看>>
file控件,以及fileList对象。
查看>>
关于多线程(GCD介绍)
查看>>
设计模式之观察者模式
查看>>
T-SQL基础(五)之增删改
查看>>
Jzoj4786 小a的强迫症
查看>>
redis配置密码
查看>>
bootstrap之辅助类
查看>>
子元素定位,父元素高度自适应
查看>>
js获取json属性值的两种方法
查看>>
[Algorithms] Queue & Priority Queue
查看>>
[React + Functional Programming ADT] Connect State ADT Based Redux Actions to a React Application
查看>>
[RxJS] Getting Input Text with Map
查看>>
[Node.js]27. Level 5: URL Building & Doing the Request
查看>>
G Data为用户提供微软安全漏洞解决方案
查看>>
java中多线程的实例代码
查看>>
保留字段数组,一定要用char
查看>>
MySQL 忘记 root 密码重置方法
查看>>