点击或拖拽改变大小

WebSocketClient 类

websocket协议的客户端实现,支持从服务器订阅,发布数据内容信息,详细参考api文档信息
Client implementation of the websocket protocol. It supports subscribing from the server and publishing data content information.
继承层次
SystemObject
  HslCommunication.WebSocketWebSocketClient

命名空间:  HslCommunication.WebSocket
程序集:  HslCommunication (在 HslCommunication.dll 中) 版本:12.0.2.0 (12.0.2.0)
语法
public class WebSocketClient : IDisposable

WebSocketClient 类型公开以下成员。

构造函数
  名称说明
公共方法WebSocketClient(String)
使用指定的url来实例化一个默认的对象,例如 ws://127.0.0.1:1883/A/B?C=123456 或是 ws://www.hslcommunication.cn:1883
Use the specified url to instantiate a default object, such as ws://127.0.0.1:1883/A/B?C=123456 or ws://www.hslcommunication.cn:1883s
公共方法WebSocketClient(String, Int32)
使用指定的ip,端口来实例化一个默认的对象
Use the specified ip and port to instantiate a default objects
公共方法WebSocketClient(String, Int32, String)
使用指定的ip,端口,额外的url信息来实例化一个默认的对象
Use the specified ip, port, and additional url information to instantiate a default object
Top
属性
  名称说明
公共属性ConnectTimeOut
获取或设置当前客户端的连接超时时间,默认10,000毫秒,单位ms
Gets or sets the connection timeout of the current client. The default is 10,000 milliseconds. The unit is ms.
公共属性IpAddress
Mqtt服务器的ip地址
IP address of Mqtt server
公共属性IsClosed
获取当前的客户端状态是否关闭了连接,当自己手动处理网络异常事件的时候,在重连之前就需要判断是否关闭了连接。
Obtain whether the current client status has closed the connection. When manually handling network abnormal events, you need to determine whether the connection is closed before reconnecting.
公共属性代码示例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
公共属性Port
端口号。默认1883
The port number. Default 1883
Top
方法
  名称说明
公共方法ConnectClose
关闭与Websocket服务器的连接。
Close the connection to the Mqtt server.
公共方法ConnectCloseAsync
关闭与Websocket服务器的连接。
Close the connection to the Mqtt server.
公共方法ConnectServer
连接服务器,实例化客户端之后,至少要调用成功一次,如果返回失败,那些请过一段时间后重新调用本方法连接。
After connecting to the server, the client must be called at least once after instantiating the client. If the return fails, please call this method to connect again after a period of time.
公共方法ConnectServer(String)
连接服务器,实例化客户端之后,至少要调用成功一次,如果返回失败,那些请过一段时间后重新调用本方法连接。
After connecting to the server, the client must be called at least once after instantiating the client. If the return fails, please call this method to connect again after a period of time.
公共方法ConnectServerAsync
连接服务器,实例化客户端之后,至少要调用成功一次,如果返回失败,那些请过一段时间后重新调用本方法连接。
After connecting to the server, the client must be called at least once after instantiating the client. If the return fails, please call this method to connect again after a period of time.
公共方法ConnectServerAsync(String)
连接服务器,实例化客户端之后,至少要调用成功一次,如果返回失败,那些请过一段时间后重新调用本方法连接。
After connecting to the server, the client must be called at least once after instantiating the client. If the return fails, please call this method to connect again after a period of time.
公共方法Dispose
释放被 WebSocketClient 使用的所有资源
受保护的方法Dispose(Boolean)
释放当前的对象
公共方法Equals (继承自 Object。)
受保护的方法Finalize (继承自 Object。)
公共方法GetHashCode (继承自 Object。)
公共方法GetType (继承自 Object。)
受保护的方法MemberwiseClone (继承自 Object。)
公共方法SendServer(String)
发送数据到WebSocket的服务器
Send data to WebSocket server
公共方法SendServer(Boolean, String)
发送数据到WebSocket的服务器,可以指定是否进行掩码操作
Send data to the WebSocket server, you can specify whether to perform a mask operation
公共方法SendServer(Int32, Boolean, Byte)
发送自定义的命令到WebSocket服务器,可以指定操作码,是否掩码操作,原始字节数据
Send custom commands to the WebSocket server, you can specify the operation code, whether to mask operation, raw byte data
公共方法ToString (重写 ObjectToString.)
公共方法UseSSL(X509Certificate)
使用一个证书来初始化 SSL/TLS 通信
Use a certificate to initiate SSL/TLS communication
公共方法UseSSL(String)
使用一个证书路径来初始化 SSL/TLS 通信
Use a certificate path to initialize SSL/TLS communication
Top
事件
  名称说明
公共事件OnClientApplicationMessageReceive
websocket的消息收到时触发
Triggered when a websocket message is received
公共事件OnClientConnected
当客户端连接成功触发事件,就算是重新连接服务器后,也是会触发的
The event is triggered when the client is connected successfully, even after reconnecting to the server.
公共事件OnNetworkError
当网络发生异常的时候触发的事件,用户应该在事件里进行重连服务器
Top
扩展方法
  名称说明
公共扩展器方法ToJsonString
获取当前对象的JSON格式表示的字符串。
Gets the string represented by the JSON format of the current object.
(由 HslExtension 定义。)
Top
示例
本客户端使用起来非常的方便,基本就是实例化,绑定一个数据接收的事件即可,如下所示
简单的实例化
private WebSocketClient webSocketClient;

public void Start( )
{
    webSocketClient = new WebSocketClient( "127.0.0.1", 1883 );
    webSocketClient.OnClientApplicationMessageReceive += WebSocketClient_OnClientApplicationMessageReceive;
    OperateResult connect = webSocketClient.ConnectServer( );
    if (connect.IsSuccess)
    {
        Console.WriteLine( "connect successful" );
    }
    else
    {
        // 连接失败。需要等会重新连接,需要注意的是,对同一个实例来说,OnClientApplicationMessageReceive不能重复绑定事件
        // Connection failed. Need to wait for reconnection, it should be noted that, for the same instance, OnClientApplicationMessageReceive can not repeatedly bind events
        Console.WriteLine( "connect failed" );
    }

    // 当连接成功后,网络发生了异常。客户端会自动重新连接的。
    // When the connection was successful, an exception occurred on the network. The client will automatically reconnect.
}

private void WebSocketClient_OnClientApplicationMessageReceive( WebSocketMessage message )
{
    Console.WriteLine( message.ToString( ) );
}
假设我们需要发数据给服务端,那么可以参考如下的方式
发送数据
public void button_Click(object sender, EventArgs e )
{
    webSocketClient.SendServer( "This is a message from hslcommunication" );
}
如果我们需要搭配服务器来做订阅推送的功能的话,写法上会稍微有点区别,按照下面的代码来写。
订阅操作
private WebSocketClient webSocketClient;

public void Start( )
{
    webSocketClient = new WebSocketClient( "127.0.0.1", 1883 );
    // 连接上服务器的时候触发,在断线重连的时候也会触发,如果使用发送服务器实现订阅的方式,在下面的事件里订阅是合理的
    // Triggered when connected to the server, it will also trigger when disconnected and reconnected. 
    // If the sending server is used to implement the subscription, the subscription is reasonable in the following events
    webSocketClient.OnClientConnected += ( ) => 
    {
        // 订阅的内容添加在这里
        // Subscribed content added here
        webSocketClient.SendServer( "A" );
    };
    webSocketClient.OnClientApplicationMessageReceive += WebSocketClient_OnClientApplicationMessageReceive;
    OperateResult connect = webSocketClient.ConnectServer( );
    if (connect.IsSuccess)
    {
        Console.WriteLine( "connect successful" );
    }
    else
    {
        // 连接失败。需要等会重新连接,需要注意的是,对同一个实例来说,OnClientApplicationMessageReceive不能重复绑定事件
        // Connection failed. Need to wait for reconnection, it should be noted that, for the same instance, OnClientApplicationMessageReceive can not repeatedly bind events
        Console.WriteLine( "connect failed" );
    }

    // 当连接成功后,网络发生了异常。客户端会自动重新连接的。
    // When the connection was successful, an exception occurred on the network. The client will automatically reconnect.

}

private void WebSocketClient_OnClientApplicationMessageReceive( WebSocketMessage message )
{
    // 一般来说,一个客户端订阅一个topic,如果要订阅多个的话,message就要区分主题,需要采用json格式的数据
    // Generally, a client subscribes to a topic. If you want to subscribe to multiple topics, 
    // the message must distinguish between topics, and payload in json format is required.
    Console.WriteLine( message.ToString( ) );
}
当网络发生异常的时候,我们需要这么来进行重新连接。
异常重连
private WebSocketClient webSocketClient;

public void Start( )
{
    webSocketClient = new WebSocketClient( "127.0.0.1", 1883 );
    // 连接上服务器的时候触发,在断线重连的时候也会触发,如果使用发送服务器实现订阅的方式,在下面的事件里订阅是合理的
    // Triggered when connected to the server, it will also trigger when disconnected and reconnected. 
    // If the sending server is used to implement the subscription, the subscription is reasonable in the following events
    webSocketClient.OnClientConnected += ( ) =>
    {
        // 订阅的内容添加在这里
        // Subscribed content added here
        webSocketClient.SendServer( "A" );
    };
    webSocketClient.OnNetworkError += ( object sender, EventArgs e ) =>
    {
        // 当网络异常的时候触发,可以在此处重连服务器
        if (sender is WebSocketClient client)
        {
            // 开始重连服务器,直到连接成功为止
            client.LogNet?.WriteInfo( "网络异常,准备10秒后重新连接。" );
            while (true)
            {
                // 每隔10秒重连
                System.Threading.Thread.Sleep( 10_000 );
                client.LogNet?.WriteInfo( "准备重新连接服务器..." );
                OperateResult connectResult = client.ConnectServer( );
                if (connectResult.IsSuccess)
                {
                    client.LogNet?.WriteInfo( "连接服务器成功!" );
                    break;
                }
                client.LogNet?.WriteInfo( "连接失败,准备10秒后重新连接。" );
            }
        }
    };
    webSocketClient.OnClientApplicationMessageReceive += WebSocketClient_OnClientApplicationMessageReceive;
    OperateResult connect = webSocketClient.ConnectServer( );
    if (connect.IsSuccess)
    {
        Console.WriteLine( "connect successful" );
    }
    else
    {
        // 连接失败。需要等会重新连接,需要注意的是,对同一个实例来说,OnClientApplicationMessageReceive不能重复绑定事件
        // Connection failed. Need to wait for reconnection, it should be noted that, for the same instance, OnClientApplicationMessageReceive can not repeatedly bind events
        Console.WriteLine( "connect failed" );
    }

    // 当连接成功后,网络发生了异常。客户端会自动重新连接的。
    // When the connection was successful, an exception occurred on the network. The client will automatically reconnect.

}

private void WebSocketClient_OnClientApplicationMessageReceive( WebSocketMessage message )
{
    // 一般来说,一个客户端订阅一个topic,如果要订阅多个的话,message就要区分主题,需要采用json格式的数据
    // Generally, a client subscribes to a topic. If you want to subscribe to multiple topics, 
    // the message must distinguish between topics, and payload in json format is required.
    Console.WriteLine( message.ToString( ) );
}
参见