我的websocket客户端需要通过包含base64编码图像的大型消息发送。现在,这暂时放慢了速度,我想......也许我应该在ASP.NET Core 2.0中增加我的websocket服务器的ReceiveBufferSize。
不幸的是......它似乎完全忽略了我的设置缓冲区大小......
阅读文档,这是设置ReceiveBufferSize的唯一方法,我发现:
WebSocketOptions webSocketOptions = new WebSocketOptions()
{
ReceiveBufferSize = 8192
};
app.UseWebSockets(webSocketOptions);
连接开始使用ApiController将HttpContext传递给' Service'包含此方法:
public async Task Register(string hub, HttpContext httpContext)
{
if (httpContext.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();
await _websocketServer.StartJoinHubWithId(webSocket, "hub", hub);
}
}
然后将其传递给WebsocketHandler类,该类驻留在一个单独的书面库中,包含此方法为一些眼睛漂白做好准备:
private async Task ReadHandler(WebSocket socket, string hub, string clientId)
{
byte[] buffer = new byte[8192];
try
{
int mode = 0;
string partialReceived = "";
while (socket.State == WebSocketState.Open)
{
_isrunning = true;
WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
_isrunning = false;
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
if (result.EndOfMessage)
{
if (result.MessageType == 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
if (message.Length > 0)
{
if (message.Contains("PARTIAL-DATA,START"))
{
mode = 1;
}
else if (message.Contains("PARTIAL-DATA,END"))
{
OnWebsocketMessageReceived(partialReceived, hub, clientId);
partialReceived = "";
mode = 0;
}
switch (mode)
{
case 0:
if (!message.Contains("PARTIAL-DATA"))
{
OnWebsocketMessageReceived(message, hub, clientId);
}
break;
case 1:
if (message.Contains("PARTIAL-DATA,"))
{
if (!message.Contains("PARTIAL-DATA,START") &&
!message.Contains("PARTIAL-DATA,END"))
{
partialReceived = partialReceived + message.Substring(13);
}
}
else
{
Debug.WriteLine(
"ERROR, PARTIAL DATA DID NOT START WITH PREFIX: PARTIAL-DATA, OR HAS START OR END IN ITS PREFIX");
mode = 0;
}
break;
}
}
}
Array.Clear(buffer, 0, buffer.Length);
}
}
}
await Stop(hub, clientId);
}
catch (WebSocketException e)
{
Debug.WriteLine("Websocket client closed without calling abort.");
Debug.WriteLine(e.ToString());
await Stop(hub, clientId);
}
}
最后,结果如下:
从之前的测试中,我可以看出只收到了部分发送字符串。
这告诉我它仍然使用默认的4 kb缓冲区。我不知道如何解决这个问题。