第一篇博客,简要介绍一下用SuperWebSocket搭建WebSocket的服务端
做了一个WebSocket的Demo,但是我不建议用 SuperWebSocket实现 ,原因有几个,如果有别的更好用的框架,也请大家留言。(肯定是有的,只是我现在没时间去研究)
SuperWebSocket 个人观点:
使用SuperWebSocket纯属为了达到效果。
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketEngine;
using SuperWebSocket;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
///
/// 服务端实例
///
public WebSocketServer WebSocket;
///
/// 客户端实例
///
WebSocketSession session;
bool OpenServer(int port, string serverName, bool isUseCertificate = false, string serverStoreName = "", string serverSecurity = "", string serverThumbprint = "")
{
WebSocket = new WebSocketServer();
var serverConfig = new ServerConfig
{
Name = serverName,
MaxConnectionNumber = 10000, //最大允许的客户端连接数目,默认为100。
Mode = SocketMode.Tcp,
Port = port, //服务器监听的端口。
ClearIdleSession = false, //true或者false, 是否清除空闲会话,默认为false。
ClearIdleSessionInterval = 120,//清除空闲会话的时间间隔,默认为120,单位为秒。
ListenBacklog = 10,
ReceiveBufferSize = 64 * 1024, //用于接收数据的缓冲区大小,默认为2048。
SendBufferSize = 64 * 1024, //用户发送数据的缓冲区大小,默认为2048。
KeepAliveInterval = 1, //keep alive消息发送时间间隔。单位为秒。
KeepAliveTime = 60, //keep alive失败重试的时间间隔。单位为秒。
SyncSend = false
};
bool isSetuped = false;
SocketServerFactory socketServerFactory = null;
//开启wss 使用证书
if (isUseCertificate)
{
serverConfig.Security = serverSecurity;
serverConfig.Certificate = new SuperSocket.SocketBase.Config.CertificateConfig
{
StoreName = serverStoreName,
StoreLocation = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
Thumbprint = serverThumbprint
};
socketServerFactory = new SocketServerFactory();
}
isSetuped = this.WebSocket.Setup(new RootConfig(), serverConfig, socketServerFactory);
if (isSetuped)
{
Console.WriteLine("打开成功");
}
else
{
Console.WriteLine("打开失败");
}
this.WebSocket.NewSessionConnected += NewSessionConnected;
this.WebSocket.NewMessageReceived += NewMessageReceived;
this.WebSocket.SessionClosed += SessionClosed;
isSetuped = this.WebSocket.Start();
if (isSetuped)
{
Console.WriteLine("启动成功...");
setText("Server Listen at " + this.WebSocket.Listeners[0].EndPoint.Port.ToString());
this._isRunning = true;
this._thread = new Thread(new ThreadStart(ProcessMaintainance));
this._thread.Start();
}
else
{
Console.WriteLine("启动失败");
}
return isSetuped;
}
///
/// 新链接触发事件
///
///
void NewSessionConnected(WebSocketSession session)
{
try
{
this.session = session;//获取新连接的客户端
string message = string.Format("New Session Connected:{0}, Path:{1}, Host:{2}, IP:{3}",
session.SessionID.ToString(), session.Path, session.Host, session.RemoteEndPoint);
Console.WriteLine("新链接" + message);
NewConnected?.Invoke(session);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
///
/// 客户端链接关闭触发事件
///
///
///
void SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
string message = string.Format("Session Close:{0}, Path:{1}, IP:{2}", value.ToString(), session.Path, session.RemoteEndPoint);
Console.WriteLine(message);
Closed?.Invoke(session);
}
///
/// 后台线程,输出连接客户端
///
void ProcessMaintainance()
{
do
{
try
{
Console.WriteLine("Display Session Info:" + this.WebSocket.SessionCount);
foreach (WebSocketSession session in this.WebSocket.GetAllSessions())
{
string message = string.Format("ID:{0}, Remote:{1}, Path:{2}, LastActiveTime:{3}, StartTime:{4}",
session.SessionID, session.RemoteEndPoint, session.Path
, session.LastActiveTime, session.StartTime);
Console.WriteLine(message);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
System.Threading.Thread.Sleep(5 * 60000);
} while (this._isRunning);
}
///
/// 发送消息
///
/// 客户端连接
/// 消息内容
void SendMessage(WebSocketSession session, string message)
{
Task.Factory.StartNew(() => { if (session != null && session.Connected) session.Send(message); });
}
///
/// 发送消息
///
/// 客户端连接
/// 消息内容
void SendMessage(WebSocketSession session, byte[] message)
{
Task.Factory.StartNew(() => { if (session != null && session.Connected) session.Send(message, 0, message.Length); });
}
///
/// 消息触发事件
///
///
///
void NewMessageReceived(WebSocketSession session, string value)
{
try
{
Console.WriteLine("Receive:" + value.ToString() + " ClientIP:" + session.RemoteEndPoint);
if (value.ToString().Equals("IsHere**"))//客户端定时发送心跳,维持链接
{
return;
}
else
{
MessageReceived?.Invoke(session, value.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
WebSocket在线测试地址:
http://www.websocket-test.com/
///
/// 点击发送
///
///
///
private void Button2_Click(object sender, EventArgs e)
{
SendMessage(this.session, "你好,这里是8000端口");
}
///
/// 启动服务器
///
///
///
private void Button1_Click(object sender, EventArgs e)
{
OpenServer(8000, "127.0.0.1");
}