Skip to content

Commit

Permalink
Adding the possibility of defining headers for web socket client.
Browse files Browse the repository at this point in the history
  • Loading branch information
behnammby committed Mar 8, 2022
1 parent 7a2f692 commit cd7f23d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
7 changes: 4 additions & 3 deletions src/Ninja.WebSocketClient/NinjaWebSocket.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Buffers;
using Ninja.WebSocketClient.Options;
using System.Buffers;

namespace Ninja.WebSocketClient
{
Expand All @@ -22,10 +23,10 @@ public class NinjaWebSocket
public event Func<Exception?, Task>? OnClosed;
public event Func<ReadOnlySequence<byte>?, Task>? OnReceived;

public NinjaWebSocket(string url)
public NinjaWebSocket(string url, Headers? headers = null)
{
_url = url;
_webSocketPipe = new WebSocketDuplexPipe();
_webSocketPipe = new WebSocketDuplexPipe(headers);
}

public async Task StartAsync(CancellationToken ct = default)
Expand Down
12 changes: 12 additions & 0 deletions src/Ninja.WebSocketClient/Options/Headers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Ninja.WebSocketClient.Options
{
public class Headers : Dictionary<string, string>
{
public Headers AddHeader(string key, string value)
{
this[key] = value;

return this;
}
}
}
18 changes: 14 additions & 4 deletions src/Ninja.WebSocketClient/Transport/WebSocketDuplexPipe.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System.IO.Pipelines;
using Ninja.WebSocketClient.Options;
using System.IO.Pipelines;
using System.Net.WebSockets;

namespace Ninja.WebSocketClient
{
internal class WebSocketDuplexPipe : IDuplexPipe
{
private ClientWebSocket? _webSocket;
private readonly Headers? _headers;
private IDuplexPipe? _transport;
private IDuplexPipe? _application;
private volatile bool _aborted;
Expand All @@ -18,15 +20,23 @@ internal class WebSocketDuplexPipe : IDuplexPipe

public PipeWriter Output => _transport!.Output;

public WebSocketDuplexPipe()
public WebSocketDuplexPipe(Headers? headers = null)
{

_headers = headers;
}

public async Task StartAsync(string url, CancellationToken ct = default)
{
_webSocket = new ClientWebSocket();

if (_headers != null)
{
foreach (var header in _headers)
{
_webSocket.Options.SetRequestHeader(header.Key, header.Value);
}
}

try
{
await _webSocket.ConnectAsync(new Uri(url), ct);
Expand Down Expand Up @@ -100,7 +110,7 @@ private async Task ProcessSocketAsync(WebSocket socket)
private async Task StartReceiving(WebSocket socket)
{
try
{
{
while (true)
{
ValueWebSocketReceiveResult receiveResult;
Expand Down

0 comments on commit cd7f23d

Please sign in to comment.