Repository navigation
C# Client: 送信時のレースコンディションを解消 #98
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 4 commits
c5e7964
57143cd
6ac0bca
825a1c5
d6642d5
b8a4adb
c24be8c
3c6d0ca
5054bf6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -38,17 +38,87 @@ | |
| volatile int pingInterval; | ||
| volatile uint lastPingTime; | ||
| CancellationTokenSource pingerDelayCanceller; | ||
| SemaphoreSlim sendSemaphore; | ||
| bool closed; | ||
|
|
||
| TaskCompletionSource<Task> senderTaskSource; | ||
| TaskCompletionSource<Task> pingerTaskSource; | ||
| readonly object senderLock; | ||
|
|
||
| BlockingCollection<byte[]> evBufPool; | ||
| uint evSeqNum; | ||
|
|
||
| Logger logger; | ||
|
|
||
| class WebSockConn : IDisposable | ||
| { | ||
| ClientWebSocket client; | ||
| SemaphoreSlim sendSemaphore; | ||
| bool closed; | ||
|
|
||
| public WebSockConn(ClientWebSocket client) | ||
| { | ||
| this.client = client; | ||
| this.sendSemaphore = new SemaphoreSlim(1, 1); | ||
| this.closed = false; | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| client.Dispose(); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. sendSemaphoreをDisposeしてないことに気づいてしまったが、Disposeしてしまうと、 |
||
| } | ||
|
|
||
| public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> seg, CancellationToken ct) | ||
| { | ||
| return client.ReceiveAsync(seg, ct); | ||
| } | ||
|
|
||
| public async Task Send(ArraySegment<byte> msg, CancellationToken ct) | ||
| { | ||
| if (closed) | ||
| { | ||
| // SendCloseがsemaphore握りっぱなしになる対策で先にチェック | ||
| // ここすり抜けてsemaphore待ってしまったらご愁傷さま…… | ||
| return; | ||
| } | ||
|
|
||
| await sendSemaphore.WaitAsync(ct); | ||
| try | ||
| { | ||
| if (closed) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| await client.SendAsync(msg, WebSocketMessageType.Binary, true, ct); | ||
| } | ||
| finally | ||
| { | ||
| sendSemaphore.Release(); | ||
| } | ||
| } | ||
|
|
||
| public async Task SendClose(string msg, CancellationToken ct) | ||
| { | ||
| await sendSemaphore.WaitAsync(ct); | ||
| try | ||
| { | ||
| if (closed) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| closed = true; | ||
|
|
||
| var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); | ||
| cts.CancelAfter(SendCloseTimeout); | ||
| await client.CloseAsync(WebSocketCloseStatus.NormalClosure, msg, cts.Token); | ||
| } | ||
| finally | ||
| { | ||
| sendSemaphore.Release(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// コンストラクタ | ||
| /// </summary> | ||
|
|
@@ -66,8 +136,7 @@ | |
| this.hmac = hmac; | ||
| this.pingInterval = calcPingInterval(room.ClientDeadline); | ||
| this.pingerDelayCanceller = new CancellationTokenSource(); | ||
| this.sendSemaphore = new SemaphoreSlim(1, 1); | ||
| this.closed = false; | ||
| this.senderLock = new object(); | ||
|
|
||
| this.evSeqNum = 0; | ||
| this.evBufPool = new BlockingCollection<byte[]>( | ||
|
|
@@ -147,7 +216,10 @@ | |
| { | ||
| senderTaskSource.TrySetCanceled(); | ||
| pingerTaskSource.TrySetCanceled(); | ||
| cts.Cancel(); | ||
| lock (senderLock) | ||
| { | ||
| cts.Cancel(); | ||
| } | ||
| if (connected) | ||
| { | ||
| connected = false; | ||
|
|
@@ -214,7 +286,7 @@ | |
| /// <summary> | ||
| /// Websocketで接続する | ||
| /// </summary> | ||
| private async Task<ClientWebSocket> Connect(CancellationToken ct) | ||
| private async Task<WebSockConn> Connect(CancellationToken ct) | ||
| { | ||
| var ws = new ClientWebSocket(); | ||
| var authdata = authgen.GenerateBearer(authKey, clientId); | ||
|
|
@@ -232,13 +304,13 @@ | |
| SetTcpNoDelay(ws); | ||
|
|
||
| logger?.Info("connected"); | ||
| return ws; | ||
| return new WebSockConn(ws); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Event受信ループ | ||
| /// </summary> | ||
| private async Task Receiver(ClientWebSocket ws, CancellationToken ct) | ||
| private async Task Receiver(WebSockConn ws, CancellationToken ct) | ||
| { | ||
| try | ||
| { | ||
|
|
@@ -295,7 +367,7 @@ | |
| /// <summary> | ||
| /// Eventの受信 | ||
| /// </summary> | ||
| private async Task<Event> ReceiveEvent(ClientWebSocket ws, CancellationToken ct) | ||
| private async Task<Event> ReceiveEvent(WebSockConn ws, CancellationToken ct) | ||
| { | ||
| var buf = evBufPool.Take(ct); | ||
| try | ||
|
|
@@ -310,7 +382,7 @@ | |
| { | ||
| // iOSでごく稀にws.CloseAsync()が返ってこないことがあるので別Taskで実行 | ||
| // Semaphoreを握りっぱなしになるけどこの接続は終了するので基本的には問題ない | ||
| Task.Run(async () => await SendClose(ws, ret.CloseStatusDescription, ct)); | ||
| Task.Run(async () => await ws.SendClose(ret.CloseStatusDescription, ct)); | ||
|
Check warning on line 385 in wsnet2-unity/Assets/WSNet2/Scripts/Core/Connection.cs
|
||
|
|
||
| switch (ret.CloseStatus) | ||
| { | ||
|
|
@@ -354,21 +426,35 @@ | |
| /// </summary> | ||
| /// <param name="seqNum">開始Msg通し番号</param> | ||
| /// <param name="ct">ループ停止するトークン</param> | ||
| private async Task Sender(ClientWebSocket ws, int seqNum, CancellationToken ct) | ||
| private async Task Sender(WebSockConn ws, int seqNum, CancellationToken ct) | ||
| { | ||
| while (true) | ||
| { | ||
| msgPool.Wait(ct); | ||
|
|
||
| ArraySegment<byte>? msg; | ||
| while ((msg = msgPool.Take(seqNum)).HasValue) | ||
| if (!msgPool.Wait(ct)) | ||
| { | ||
| if (ct.IsCancellationRequested) | ||
| // ctがキャンセルされているとき falseが返るので終了 | ||
| return; | ||
| } | ||
|
|
||
| while (true) { | ||
| ArraySegment<byte>? msg; | ||
| lock (senderLock) | ||
| { | ||
| return; // ctのキャンセルで終了 | ||
| // ctのキャンセルで終了, キャンセル後にmsgPool.Takeしない | ||
| if (ct.IsCancellationRequested) | ||
| { | ||
| return; | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Senderが終了するときにmsgPool.hasMsgを復活させるようにした。 |
||
| } | ||
|
|
||
| msg = msgPool.Take(seqNum); | ||
| } | ||
|
|
||
| if (!msg.HasValue) { | ||
| break; | ||
| } | ||
|
|
||
| await Send(ws, msg.Value, ct); | ||
| NetworkInformer.OnRoomSend(room, msg.Value); | ||
| await ws.Send(msg.Value, ct); | ||
| seqNum++; | ||
| } | ||
| } | ||
|
|
@@ -377,7 +463,7 @@ | |
| /// <summary> | ||
| /// Ping送信ループ | ||
| /// </summary> | ||
| private async Task Pinger(ClientWebSocket ws, CancellationToken ct) | ||
| private async Task Pinger(WebSockConn ws, CancellationToken ct) | ||
| { | ||
| var msg = new MsgPing(hmac); | ||
|
|
||
|
|
@@ -391,7 +477,8 @@ | |
| var interval = Task.Delay(pingInterval, pingerDelayCanceller.Token); | ||
| var time = (uint)msg.SetTimestamp(); | ||
| lastPingTime = time; | ||
| await Send(ws, msg.Value, ct); | ||
| NetworkInformer.OnRoomSend(room, msg.Value); | ||
| await ws.Send(msg.Value, ct); | ||
| try | ||
| { | ||
| await interval; | ||
|
|
@@ -408,57 +495,6 @@ | |
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// websocketメッセージを送信 | ||
| /// </summary> | ||
| private async Task Send(ClientWebSocket ws, ArraySegment<byte> msg, CancellationToken ct) | ||
| { | ||
| if (closed) | ||
| { | ||
| // SendCloseがsemaphore握りっぱなしになる対策で先にチェック | ||
| // ここすり抜けてsemaphore待ってしまったらご愁傷さま…… | ||
| return; | ||
| } | ||
|
|
||
| await sendSemaphore.WaitAsync(ct); | ||
| try | ||
| { | ||
| if (closed) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| NetworkInformer.OnRoomSend(room, msg); | ||
| await ws.SendAsync(msg, WebSocketMessageType.Binary, true, ct); | ||
| } | ||
| finally | ||
| { | ||
| sendSemaphore.Release(); | ||
| } | ||
| } | ||
|
|
||
| private async Task SendClose(ClientWebSocket ws, string msg, CancellationToken ct) | ||
| { | ||
| await sendSemaphore.WaitAsync(ct); | ||
| try | ||
| { | ||
| if (closed) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| closed = true; | ||
|
|
||
| var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); | ||
| cts.CancelAfter(SendCloseTimeout); | ||
| await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, msg, cts.Token); | ||
| } | ||
| finally | ||
| { | ||
| sendSemaphore.Release(); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Pong受信時の処理 | ||
| /// </summary> | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
copilotくんがvolatileつけた方がいいってさ。
https://github.com/KLab/wsnet2/tasks/7f4b0bc8-9c33-4006-83fc-09eabb4e87a6?session_id=e404aae2-e73b-4d72-94cd-f51fbd51f39e
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ありがとうございます
volatileつけました