Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,22 +93,22 @@ private async Task RunReadFromClientLoopAsync(PipeWriter websocketPipeWriter, We
await readyToRunTask;

var bufferArray = new byte[ReaderWriterBufferSize];
var isRequestCompleted = false;
var isPipeCompleted = false;

var reader = new GrpcWebSocketBufferReader();
var bufferWriter = new ArrayBufferWriter<byte>();
var consumed = 0;
try
{
while (webSocket.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested && !isRequestCompleted)
while (webSocket.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested)
{
var result = await webSocket.ReceiveAsync(bufferArray, cancellationToken);
if (result.MessageType != WebSocketMessageType.Binary) continue;
if (result.MessageType != WebSocketMessageType.Binary)
continue;

bufferWriter.Write(bufferArray.AsSpan(0, result.Count));

while (reader.TryRead(bufferWriter.WrittenMemory.Slice(consumed), out var readResult))
while (!isPipeCompleted && reader.TryRead(bufferWriter.WrittenMemory.Slice(consumed), out var readResult))
{
switch (readResult.Type)
{
Expand All @@ -125,7 +125,8 @@ private async Task RunReadFromClientLoopAsync(PipeWriter websocketPipeWriter, We
await websocketPipeWriter.FlushAsync(cancellationToken);
break;
case GrpcWebSocketBufferReader.BufferReadResultType.Trailer:
isRequestCompleted = true;
await websocketPipeWriter.CompleteAsync();
isPipeCompleted = true;
break;
}

Expand All @@ -147,7 +148,7 @@ private async Task RunReadFromClientLoopAsync(PipeWriter websocketPipeWriter, We
catch (Exception e) when (e is ConnectionAbortedException || e is WebSocketException)
{
// When the WebSocket connection has been closed, Ignore ConnectionAbortedException and WebSocketException.
if (!isRequestCompleted)
if (!isPipeCompleted)
{
await websocketPipeWriter.CompleteAsync(new IOException("The request was aborted.", e));
isPipeCompleted = true;
Expand All @@ -169,7 +170,7 @@ private async Task RunWriteToClientLoopAsync(Pipe writerPipe, WebSocket webSocke
// Wait until the features are ready to run.
await readyToRunTask;

using var stream = writerPipe.Reader.AsStream();
await using var stream = writerPipe.Reader.AsStream();
var bufferArray = new byte[ReaderWriterBufferSize];
var readLen = 0;
while ((readLen = await stream.ReadAsync(bufferArray, cancellationToken)) > 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public partial class GrpcWebSocketBridgeHandler
{
private static PipeOptions PipeOptions { get; } = new PipeOptions();

private static IClientWebSocket CreateClientWebSocket() => new SystemNetWebSocketsClientWebSocket();
private IClientWebSocket CreateClientWebSocket() => new SystemNetWebSocketsClientWebSocket(CookieContainer);


public GrpcWebSocketBridgeHandler(bool forceWebSocketMode = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ public partial class GrpcWebSocketBridgeHandler
{
private static PipeOptions PipeOptions { get; } = new PipeOptions(readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false);

private static IClientWebSocket CreateClientWebSocket() =>
private IClientWebSocket CreateClientWebSocket() =>
#if UNITY_WEBGL && !UNITY_EDITOR
new JsWebSocketsClientWebSocket();
#else
new SystemNetWebSocketsClientWebSocket();
new SystemNetWebSocketsClientWebSocket(CookieContainer);
#endif

public GrpcWebSocketBridgeHandler(bool forceWebSocketMode = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ namespace GrpcWebSocketBridge.Client
{
public partial class GrpcWebSocketBridgeHandler : DelegatingHandler
{
public CookieContainer? CookieContainer { get; set; }

private readonly HashSet<IClientWebSocket> _ongoingWebSockets = new HashSet<IClientWebSocket>();
private readonly bool _forceWebSocketMode = false;

Expand Down
10 changes: 5 additions & 5 deletions src/GrpcWebSocketBridge.Client/Unity/JsWebSocket.jslib
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,18 @@
var connection = connections[handle];

connection.socket = new WebSocket(connections[handle].url, connections[handle].subProtocol);

connection.socket.binaryType = 'arraybuffer';
connection.socket.onopen = function (e) {
dynCall('vi', connection.onConnected, [connection.id]);
getWasmTableEntry(connection.onConnected)(connection.id);
};
connection.socket.onclose = function (e) {
dynCall('viii', connection.onClose, [connection.id, e.code, e.wasClean ? 1 : 0]);
getWasmTableEntry(connection.onClose)(connection.id, e.code, e.wasClean ? 1 : 0);
};
connection.socket.onmessage = function (e) {
var buffer = _malloc(e.data.byteLength);
HEAPU8.set(new Uint8Array(e.data), buffer);
dynCall('viii', connection.onReceive, [connection.id, buffer, e.data.byteLength]);
getWasmTableEntry(connection.onReceive)(connection.id, buffer, e.data.byteLength);
_free(buffer);
};
},
Expand Down Expand Up @@ -72,4 +72,4 @@

autoAddDeps(JsWebSocketLibrary, '$connections');
autoAddDeps(JsWebSocketLibrary, '$connectionsSequence');
mergeInto(LibraryManager.library, JsWebSocketLibrary);
mergeInto(LibraryManager.library, JsWebSocketLibrary);
3 changes: 2 additions & 1 deletion src/GrpcWebSocketBridge.Client/Unity/JsWebSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ private void ThrowIfStateIsNotOpen()

public void Dispose()
{
CloseAsync(WebSocketCloseStatus.NormalClosure, "Disposed", CancellationToken.None);
_ws.Dispose();
}

Expand Down Expand Up @@ -159,7 +160,7 @@ public ValueWebSocketReceiveResult(int count, WebSocketMessageType messageType,
public class JsWebSocket
{
private static Dictionary<int, JsWebSocket> _instanceByHandle = new Dictionary<int, JsWebSocket>();

private Queue<byte[]> _queue = new Queue<byte[]>();
private TaskCompletionSource<byte[]> _receiveTcs;
private int _handle;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,11 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
};

var responseHeader = response.Headers;
var contentHeader = response.Content.Headers;
foreach (var header in webRequest.GetResponseHeaders())
{
responseHeader.TryAddWithoutValidation(header.Key, header.Value);
contentHeader.TryAddWithoutValidation(header.Key, header.Value);
}

return response;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -9,9 +10,9 @@ internal class SystemNetWebSocketsClientWebSocket : IClientWebSocket
{
private readonly System.Net.WebSockets.ClientWebSocket _clientWebSocket;

public SystemNetWebSocketsClientWebSocket()
public SystemNetWebSocketsClientWebSocket(CookieContainer? cookieContainer = null)
{
_clientWebSocket = new ClientWebSocket();
_clientWebSocket = new ClientWebSocket { Options = { Cookies = cookieContainer } };
}

public WebSocketState State => _clientWebSocket.State;
Expand Down
4 changes: 2 additions & 2 deletions src/GrpcWebSocketBridge.Client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"name": "com.cysharp.grpcwebsocketbridge",
"displayName": "GrpcWebSocketBridge",
"author": { "name": "Cysharp, Inc.", "url": "https://cysharp.co.jp/en/" },
"version": "1.4.1",
"unity": "2022.3",
"version": "1.4.2",
"unity": "6000.0",
"description": "",
"keywords": ["WebSocket", "gRPC"],
"license": "MIT",
Expand Down