点击或拖拽改变大小

WebSocketServer 类

WebSocket协议的实现,支持创建自定义的websocket服务器,直接给其他的网页端,客户端,手机端发送数据信息,详细看api文档说明
The implementation of the WebSocket protocol supports the creation of custom websocket servers and sends data information directly to other web pages, clients, and mobile phones. See the API documentation for details.
继承层次
SystemObject
  HslCommunication.Core.NetCommunicationTcpServer
    HslCommunication.WebSocketWebSocketServer

命名空间:  HslCommunication.WebSocket
程序集:  HslCommunication (在 HslCommunication.dll 中) 版本:12.0.3.0 (12.0.3.0)
语法
public class WebSocketServer : CommunicationTcpServer, 
	IDisposable

WebSocketServer 类型公开以下成员。

构造函数
  名称说明
公共方法WebSocketServer
实例化一个默认的对象
Instantiate a default object
Top
属性
  名称说明
公共属性EnableIPv6
获取或设置服务器是否支持IPv6的地址协议信息
Get or set whether the server supports IPv6 address protocol information
(继承自 CommunicationTcpServer。)
公共属性IsStarted
服务器引擎是否启动
Whether the server engine is started
(继承自 CommunicationTcpServer。)
公共属性IsTopicRetain
获取或设置当前的服务器是否对订阅主题信息缓存,方便订阅客户端立即收到结果,默认开启
Gets or sets whether the current server caches the topic information of the subscription, so that the subscription client can receive the results immediately. It is enabled by default.
公共属性KeepAlivePeriod
设置的参数,最小单位为1s,当超过设置的时间间隔必须回复PONG报文,否则服务器认定为掉线。默认120秒
Set the minimum unit of the parameter is 1s. When the set time interval is exceeded, the PONG packet must be returned, otherwise the server considers it to be offline. 120 seconds by default
公共属性KeepAliveSendInterval
获取或是设置用于保持连接的心跳时间的发送间隔。默认30秒钟,需要在服务启动之前设置
Gets or sets the sending interval of the heartbeat time used to keep the connection. 30 seconds by default, need to be set before the service starts
公共属性LogDebugMessage
记录一些调试日志的委托,将会进行输出调试文本。
The delegate that records some debug logs will output debug text.
(继承自 CommunicationTcpServer。)
公共属性代码示例LogNet
组件的日志工具,支持日志记录,只要实例化后,当前网络的基本信息,就以DEBUG等级进行输出
The component's logging tool supports logging. As long as the instantiation of the basic network information, the output will be output at DEBUG
(继承自 CommunicationTcpServer。)
公共属性OnlineCount
获取当前的在线的客户端数量
Get the current number of online clients
公共属性OnlineSessions
获取当前的在线的客户端信息,可以用于额外的分析或是显示。
公共属性Port
获取或设置服务器的端口号,如果是设置,需要在服务器启动前设置完成,才能生效。
Gets or sets the port number of the server. If it is set, it needs to be set before the server starts to take effect.
(继承自 CommunicationTcpServer。)
公共属性SocketKeepAliveTime
获取或设置客户端的Socket的心跳时间信息,这个是Socket底层自动实现的心跳包,不基于协议层实现。默认小于0,不开启心跳检测,如果需要开启,设置 60_000 比较合适,单位毫秒
Get or set the heartbeat time information of the Socket of the client. This is the heartbeat packet automatically implemented by the bottom layer of the Socket, not based on the protocol layer. The default value is less than 0, and heartbeat detection is not enabled. If you need to enable it, it is more appropriate to set 60_000, in milliseconds.
(继承自 CommunicationTcpServer。)
公共属性TopicWildcard
获取或设置是否启用订阅主题通配符的功能,默认为 False
Gets or sets whether to enable the function of subscribing to the topic wildcard, the default is False
Top
方法
  名称说明
公共方法AddSessionTopic
给一个当前的会话信息动态添加订阅的主题
Dynamically add subscribed topics to a current session message
公共方法Dispose
释放被 WebSocketServer 使用的所有资源
受保护的方法Dispose(Boolean)
释放当前的对象
公共方法Equals (继承自 Object。)
受保护的方法ExtraOnClose
关闭的时候额外执行的功能代码
(重写 CommunicationTcpServerExtraOnClose.)
受保护的方法ExtraOnStart
服务器启动的时候额外执行的功能代码
(重写 CommunicationTcpServerExtraOnStart.)
受保护的方法Finalize (继承自 Object。)
公共方法GetHashCode (继承自 Object。)
公共方法GetTrustedClients
获取受信任的客户端列表
Get a list of trusted clients
(继承自 CommunicationTcpServer。)
公共方法GetType (继承自 Object。)
受保护的方法LogDebugMsg
记录当前的日志信息
(继承自 CommunicationTcpServer。)
受保护的方法MemberwiseClone (继承自 Object。)
公共方法PublishAllClientPayload
向所有的客户端强制发送消息
Force message to all clients
公共方法PublishAllClientPayloadAsync
向所有的客户端强制发送消息
Force message to all clients
公共方法PublishClientPayload(String, String)
向订阅了topic主题的客户端发送消息
Send messages to clients subscribed to topic
公共方法PublishClientPayload(String, String, Boolean)
向订阅了topic主题的客户端发送消息
Send messages to clients subscribed to topic
公共方法PublishClientPayloadAsync(String, String)
向订阅了topic主题的客户端发送消息
Send messages to clients subscribed to topic
公共方法PublishClientPayloadAsync(String, String, Boolean)
向订阅了topic主题的客户端发送消息
Send messages to clients subscribed to topic
公共方法RemoveAndCloseSession
让Websocket客户端正常下线,调用本方法即可自由控制会话客户端强制下线操作。
Let the Websocket client go offline normally. Call this method to freely control the session client to force offline operation.
公共方法SendClientPayload
向指定的客户端发送数据
Send data to the specified client
公共方法ServerClose
关闭服务器的引擎
Shut down the server's engine
(继承自 CommunicationTcpServer。)
公共方法ServerStart
指定端口号来启动服务器的引擎
Specify the port number to start the server's engine
(继承自 CommunicationTcpServer。)
公共方法ServerStart(Int32)
指定端口号来启动服务器的引擎
Specify the port number to start the server's engine
(继承自 CommunicationTcpServer。)
公共方法SetTrustedIpAddress
设置并启动受信任的客户端登录并读写,如果为null,将关闭对客户端的ip验证
Set and start the trusted client login and read and write, if it is null, the client's IP verification will be turned off
(继承自 CommunicationTcpServer。)
受保护的方法SocketAcceptExtraCheck
当客户端的socket登录的时候额外检查的操作,并返回操作的结果信息。
The operation is additionally checked when the client's socket logs in, and the result information of the operation is returned.
(继承自 CommunicationTcpServer。)
受保护的方法ThreadPoolLogin
当客户端连接到服务器,并听过额外的检查后,进行回调的方法
Callback method when the client connects to the server and has heard additional checks
(重写 CommunicationTcpServerThreadPoolLogin(PipeTcpNet, IPEndPoint).)
公共方法ToString (重写 ObjectToString.)
公共方法UseSSL(X509Certificate)
使用SSL通信,传递一个证书的对象
(继承自 CommunicationTcpServer。)
公共方法UseSSL(String, String)
使用SSL通信,传递一个证书的路径,以及证书的密码
(继承自 CommunicationTcpServer。)
Top
事件
  名称说明
公共事件OnClientApplicationMessageReceive
websocket的消息收到时触发
Triggered when a websocket message is received
公共事件OnClientConnected
Websocket的客户端连接上来时触发
Triggered when a Websocket client connects
公共事件OnClientDisConnected
Websocket的客户端下线时触发
Triggered when Websocket client connects
Top
字段
  名称说明
受保护的字段socketServer
核心的socket服务器
(继承自 CommunicationTcpServer。)
Top
扩展方法
  名称说明
公共扩展器方法ToJsonString
获取当前对象的JSON格式表示的字符串。
Gets the string represented by the JSON format of the current object.
(由 HslExtension 定义。)
Top
示例
使用本组件库可以非常简单方便的构造属于你自己的websocket服务器,从而实现和其他的客户端进行通信,尤其是和网页进行通讯,
简单的实例化
// 定义一个对象
// Define an object
public WebSocketServer webSocketServer;

public void Start( )
{
    try
    {
        webSocketServer = new WebSocketServer( );
        webSocketServer.ServerStart( 1883 );
    }
    catch(Exception ex)
    {
        Console.WriteLine( ex.Message );
    }
}
当客户端发送数据给服务器的时候,会发一个事件,并且把当前的会话暴露出来,下面举例打印消息,并且演示一个例子,发送数据给指定的会话。
接触数据
public WebSocketServer webSocketServer;

public void Start( )
{
    try
    {
        webSocketServer = new WebSocketServer( );
        webSocketServer.OnClientApplicationMessageReceive += WebSocketServer_OnClientApplicationMessageReceive;
        // 如果要控制心跳时间,需要在ServerStart方法调用之前
        webSocketServer.KeepAliveSendInterval = TimeSpan.FromSeconds( 20 ); // 默认间隔30秒发送客户端一次心跳
        webSocketServer.KeepAlivePeriod = TimeSpan.FromSeconds( 100 );      // 如果100秒之内都没有任何的心跳回复,就认为掉线了
        webSocketServer.ServerStart( 1883 );
    }
    catch (Exception ex)
    {
        Console.WriteLine( ex.Message );
    }
}

private void WebSocketServer_OnClientApplicationMessageReceive( WebSocketSession session, WebSocketMessage message )
{
    // 当接收到客户端的数据的时候触发,session参数就是会话信息,你可以选择打印数据,或是回发数据
    // Triggered when data is received from the client. The session parameter is the session information. You can choose to print the data or send it back.
    Console.WriteLine( message.ToString( ) );
    webSocketServer.SendClientPayload( session, "I hava received your data, thank you" );
}
也可以在其他地方发送数据给所有的客户端,只要调用一个方法就可以了。
发送数据
// 以下的信息会发布到所有的连接的客户端,包括网页端或是桌面程序
// The following information will be published to all connected clients, including web or desktop
private void Button1_Click(object sender, EventArgs e )
{
    webSocketServer.PublishAllClientPayload( "This is sample data, thank you for use hslcommunication" );
}
当客户端上线之后也触发了当前的事件,我们可以手动捕获到
捕获上线事件
public WebSocketServer webSocketServer;

public void Start( )
{
    try
    {
        webSocketServer = new WebSocketServer( );
        webSocketServer.OnClientApplicationMessageReceive += WebSocketServer_OnClientApplicationMessageReceive;
        webSocketServer.OnClientConnected += ( WebSocketSession session ) =>
        {
            Console.WriteLine( session.Remote.ToString( ) + " Online" );
        };
        webSocketServer.ServerStart( 1883 );
    }
    catch (Exception ex)
    {
        Console.WriteLine( ex.Message );
    }
}


private void WebSocketServer_OnClientApplicationMessageReceive( WebSocketSession session, WebSocketMessage message )
{
    // 当接收到客户端的数据的时候触发,session参数就是会话信息,你可以选择打印数据,或是回发数据
    // Triggered when data is received from the client. The session parameter is the session information. You can choose to print the data or send it back.
    Console.WriteLine( message.ToString( ) );
    webSocketServer.SendClientPayload( session, "I hava received your data, thank you" );
}
我们再来看看一个高级的操作,实现订阅,大多数的情况,websocket被设计成了订阅发布的操作。基本本服务器可以扩展出非常复杂功能的系统,我们来看一种最简单的操作。
客户端给服务器发的数据都视为主题(topic),这样服务器就可以辨认出主题信息,并追加主题。如下这么操作。
订阅实现
public WebSocketServer webSocketServer;

public void Start( )
{
    try
    {
        webSocketServer = new WebSocketServer( );
        webSocketServer.OnClientApplicationMessageReceive += WebSocketServer_OnClientApplicationMessageReceive;
        webSocketServer.ServerStart( 1883 );
    }
    catch (Exception ex)
    {
        Console.WriteLine( ex.Message );
    }
}

private void WebSocketServer_OnClientApplicationMessageReceive( WebSocketSession session, WebSocketMessage message )
{
    // 客户端发过来的数据就是订阅的主题,服务器在收到数据后加入到订阅的数据信息里去,假如订阅的数据已经存在,会自动推送数据
    // The data sent by the client is the subject of the subscription. After receiving the data, the server adds it to the subscribed data information. 
    // If the subscribed data already exists, it will automatically push the data.
    Console.WriteLine( message.ToString( ) );
    string topic = Encoding.UTF8.GetString( message.Payload );
    if(!string.IsNullOrEmpty( topic ))
    {
        webSocketServer.AddSessionTopic( session, topic );
    }
}
然后在发布的时候,调用下面的代码。
发布数据
// 以下的信息会发布到所有的连接的客户端,包括网页端或是桌面程序
// The following information will be published to all connected clients, including web or desktop
private void Button1_Click( object sender, EventArgs e )
{
    webSocketServer.PublishClientPayload( "A", "This is sample data, thank you for use hslcommunication" );
}
可以看到,我们这里只有订阅操作,如果想要实现更为复杂的操作怎么办?丰富客户端发来的数据,携带命令,数据,就可以区分了。比如json数据。具体的实现需要看各位能力了。
参见