broersa
broersa

Reputation: 1736

WebSockets SendAsync exception

I am sending 1000 messages in a loop using SendAsync method and get the exception below on this line of code

await _ws.SendAsync(new ArraySegment<byte>(messageBuffer, offset, count), WebSocketMessageType.Text, lastMessage, _cancellationToken);

What am I doing wrong? I know somewhere must be a bottleneck because I have no sleep between the sends. Can I wait for a certain state to provent the exception below?

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=There is already one outstanding 'SendAsync' call for this WebSocket instance. ReceiveAsync and SendAsync can be called simultaneously, but at most one outstanding operation for each of them is allowed at the same time.
  Source=System
  StackTrace:
       at System.Net.WebSockets.WebSocketBase.<SendAsyncCore>d__8.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
       at zzz.Stub.WebSocketWrapper.<SendMessageAsync>d__0.MoveNext() in zzz

Upvotes: 5

Views: 6016

Answers (1)

vtortola
vtortola

Reputation: 35963

You cannot do parallel sending or receiving, keep that in mind. Since you are awaiting it seems fine.

If you have other thread sending ping or keep alive messages it may be the problem.

I use that library for load testing, so I create lot of connections and send lot of messages and it works. It is not great, but it works.

Upvotes: 5

Related Questions