我需要建立多个Web套接字连接,这些连接将永远接收更新,除非它们在某些情况下退出。我需要等待这些套接字连接,因为这个轮询更新事件的循环限制了可以一次运行的线程数,从而限制了我可以打开的连接数。
我试图通过使用信号量作为检测事件的方法来解决这个问题(通过IObserver接口观察事件)
static SemaphoreSlim send = new SemaphoreSlim(0,1);
static object newUpdate;
static numberOfClients = 0;
以及轮询和可能接收更新或终止的循环
while(true)
{
await send.WaitAsync() //wait the thread so others can start
//do some things with the updated valu and send data or possibly quit
}
以及检测事件的OnNext实现
public void OnNext(object value)
{
newUpdate = value;
for (int i = 0; i < numberOfClients; i++)
{
send.Release();
Thread.Sleep(100);
}
}
和客户端实现:
do
{
try
{
WebSocketReceiveResult result = await websocket.ReceiveAsync(buffer, CancellationToken.None);
byte[] receivedData = new byte[result.Count];
Buffer.BlockCopy(buffer.Array, 0, receivedData, 0, result.Count);
if (result.MessageType == WebSocketMessageType.Text)
{
Console.WriteLine("\nReceived message: " + Encoding.UTF8.GetString(receivedData));
}
}
catch (WebSocketException e)
{
if (websocket.State == WebSocketState.Aborted)
{
break;
}
continue;
}
if (result.EndOfMessage)
{
break;
}
}
while (websocket.State == WebSocketState.Open);
当我执行此操作时,似乎是行:
await send.WaitAsync()
在尝试调用await时,会立即使客户端代码崩溃.ReceiveAsync()并发出声响:
"Unable to read data from transport connection. An existing connection was forcibly closed by the remote host".
我有什么想法可以完成这样的事情?这是使用OWIN WebSocket扩展。