Skip to content

Commit

Permalink
Fix buffer size for old device
Browse files Browse the repository at this point in the history
  • Loading branch information
LucHeart committed Dec 29, 2023
1 parent 36383aa commit df66bd6
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 9 deletions.
2 changes: 2 additions & 0 deletions API/Controller/DeviceWebSocketController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public sealed class DeviceWebSocketController : WebsocketBaseController<IBaseRes
private readonly IRedisCollection<DeviceOnline> _devicesOnline;
private readonly IRedisConnectionProvider _redis;

public override int MaxChunkSize => 4096;

private Common.OpenShockDb.Device _currentDevice = null!;

public override void OnActionExecuting(ActionExecutingContext context)
Expand Down
11 changes: 3 additions & 8 deletions ServicesCommon/Utils/JsonWebSocketUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,16 @@ await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closure during mess
}
}

public static Task SendFullMessage<T>(T obj, WebSocket socket, CancellationToken cancelToken) =>
public static Task SendFullMessage<T>(T obj, WebSocket socket, CancellationToken cancelToken, int maxChunkSize = 256) =>
SendFullMessageBytes(JsonSerializer.SerializeToUtf8Bytes(obj), socket, cancelToken);


public static Task SendFullMessage(string json, WebSocket socket, CancellationToken cancelToken) =>
SendFullMessageBytes(Encoding.UTF8.GetBytes(json), socket, cancelToken);


public static async Task SendFullMessageBytes(byte[] msg, WebSocket socket, CancellationToken cancelToken)
public static async Task SendFullMessageBytes(byte[] msg, WebSocket socket, CancellationToken cancelToken, int maxChunkSize = 256)
{
var doneBytes = 0;

while (doneBytes < msg.Length)
{
var bytesProcessing = Math.Min(16, msg.Length - doneBytes);
var bytesProcessing = Math.Min(maxChunkSize, msg.Length - doneBytes);
var buffer = msg.AsMemory(doneBytes, bytesProcessing);

doneBytes += bytesProcessing;
Expand Down
4 changes: 3 additions & 1 deletion ServicesCommon/Websocket/WebsockBaseController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public abstract class WebsocketBaseController<T> : OpenShockControllerBase, IAsy
{
/// <inheritdoc />
public abstract Guid Id { get; }

public virtual int MaxChunkSize => 256;

/// <summary>
/// Logger
Expand Down Expand Up @@ -146,7 +148,7 @@ private async Task MessageLoop()
/// <returns></returns>
[NonAction]
protected virtual Task SendWebSocketMessage(T message, WebSocket websocket, CancellationToken cancellationToken) =>
JsonWebSocketUtils.SendFullMessage(message, websocket, cancellationToken);
JsonWebSocketUtils.SendFullMessage(message, websocket, cancellationToken, MaxChunkSize);


#endregion
Expand Down

0 comments on commit df66bd6

Please sign in to comment.