|
1 | 1 | using Solana.Unity.Rpc.Types; |
2 | 2 | using System; |
3 | | -using System.IO; |
4 | 3 | using System.Net.WebSockets; |
5 | 4 | using System.Threading; |
6 | 5 | using System.Threading.Tasks; |
@@ -58,14 +57,30 @@ protected StreamingRpcClient(string url, object logger, IWebSocket socket = defa |
58 | 57 | _connectionStats = new ConnectionStats(); |
59 | 58 | ClientSocket.ConnectionStateChangedEvent += (sender, state) => ConnectionStateChangedEvent?.Invoke(sender, state); |
60 | 59 | } |
| 60 | + |
| 61 | + /// <summary> |
| 62 | + /// Constructor that setups the client with a IWebSocket instance. |
| 63 | + /// </summary> |
| 64 | + /// <param name="url"></param> |
| 65 | + /// <param name="socket"></param> |
| 66 | + protected StreamingRpcClient(string url, IWebSocket socket) |
| 67 | + { |
| 68 | + NodeAddress = new Uri(url); |
| 69 | + ClientSocket = socket ?? new WebSocketWrapper(); |
| 70 | + _logger = null; |
| 71 | + _sem = new SemaphoreSlim(1, 1); |
| 72 | + _connectionStats = new ConnectionStats(); |
| 73 | + ClientSocket.ConnectionStateChangedEvent += (sender, state) => ConnectionStateChangedEvent?.Invoke(sender, state); |
| 74 | + } |
61 | 75 |
|
62 | 76 | /// <summary> |
63 | 77 | /// Initializes the websocket connection and starts receiving messages asynchronously. |
64 | 78 | /// </summary> |
65 | 79 | /// <returns>Returns the task representing the asynchronous task.</returns> |
66 | 80 | public async Task ConnectAsync() |
67 | 81 | { |
68 | | - _sem.Wait(); |
| 82 | + if (ClientSocket.State == WebSocketState.Open) return; |
| 83 | + await _sem.WaitAsync().ConfigureAwait(false); |
69 | 84 | try |
70 | 85 | { |
71 | 86 | if (ClientSocket.State != WebSocketState.Open) |
@@ -94,7 +109,8 @@ private void DispatchMessage(byte[] message) |
94 | 109 | /// <inheritdoc cref="IStreamingRpcClient.DisconnectAsync"/> |
95 | 110 | public async Task DisconnectAsync() |
96 | 111 | { |
97 | | - _sem.Wait(); |
| 112 | + if (ClientSocket.State == WebSocketState.Closed) return; |
| 113 | + await _sem.WaitAsync().ConfigureAwait(false); |
98 | 114 | try |
99 | 115 | { |
100 | 116 | if (ClientSocket.State == WebSocketState.Open) |
|
0 commit comments