mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-15 08:33:01 +08:00
48 lines
1.3 KiB
C#
48 lines
1.3 KiB
C#
using MQTTnet.Core.Channel;
|
|
using MQTTnet.Core.Client;
|
|
using MQTTnet.Core.Exceptions;
|
|
using System;
|
|
using System.IO;
|
|
using System.Net.WebSockets;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MQTTnet.Implementations
|
|
{
|
|
public sealed class MqttWebSocketChannel : IMqttCommunicationChannel, IDisposable
|
|
{
|
|
private ClientWebSocket _webSocket = new ClientWebSocket();
|
|
|
|
public Stream SendStream => RawStream;
|
|
public Stream ReceiveStream => RawStream;
|
|
public Stream RawStream { get; private set; }
|
|
|
|
public async Task ConnectAsync(MqttClientOptions options)
|
|
{
|
|
_webSocket = null;
|
|
|
|
try
|
|
{
|
|
_webSocket = new ClientWebSocket();
|
|
await _webSocket.ConnectAsync(new Uri(options.Server), CancellationToken.None);
|
|
|
|
RawStream = new WebSocketStream(_webSocket);
|
|
}
|
|
catch (WebSocketException exception)
|
|
{
|
|
throw new MqttCommunicationException(exception);
|
|
}
|
|
}
|
|
|
|
public Task DisconnectAsync()
|
|
{
|
|
RawStream = null;
|
|
return _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_webSocket?.Dispose();
|
|
}
|
|
}
|
|
} |