private async Task ProcessingDataConnection(DataConnectionInfo connectionInfo) { var buffer = new byte[16 * 1024]; while (connectionInfo.socket.State == WebSocketState.Open) { var ms = new MemoryStream(); try { WebSocketReceiveResult received; do { received = await connectionInfo.socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); await ms.WriteAsync(buffer, 0, received.Count); } while (!received.EndOfMessage); if (received.MessageType == WebSocketMessageType.Close) { if (connectionInfo.socket.State == WebSocketState.CloseReceived) { await connectionInfo.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); } } else { await HandleDataMessage(ms.ToArray(), connectionInfo); } } catch (Exception ex) { log.LogError($"[{connectionInfo.connectionId}]: Приполучении данных произошла ошибка: {ex.Message} "); } } }
private async Task <bool> SendData(DataConnectionInfo connectionInfo, Guid socketId, byte[] data, int size) { await using var ms = new MemoryStream(); await using var bw = new BinaryWriter(ms); bw.Write(socketId.ToByteArray()); bw.Write(size); bw.Write(data, 0, size); bw.Flush(); var encodedData = await dEncoder.Encrypt(connectionInfo.aes, connectionInfo.bufferSize, ms.ToArray()); return(await SendData(connectionInfo, encodedData)); }
private async Task EchoProcessing(DataConnectionInfo connectionInfo, byte[] payload) { var str = Encoding.UTF8.GetString(payload); var echoReq = JsonConvert.DeserializeObject <EchoReq>(str, JsonSettings.settings); var echoRes = new EchoRes { ReqId = echoReq.ReqId, ReqTimestamp = echoReq.Timestamp, ResTimestamp = DateTime.UtcNow }; var buffer = Encoding.UTF8.GetBytes(echoRes.ToJson()); await SendData(connectionInfo, Guid.Empty, buffer, buffer.Length); }
private async Task HandleDataMessage(byte[] encryptedData, DataConnectionInfo connectionInfo) { var data = await dEncoder.Decrypt(connectionInfo.aes, encryptedData); var ms = new MemoryStream(data); using var br = new BinaryReader(ms); var socketId = new Guid(br.ReadBytes(16)); var payloadSize = br.ReadInt32(); var payload = br.ReadBytes(payloadSize); if (socketId == Guid.Empty) { await EchoProcessing(connectionInfo, payload); } else { await SocketProcessing(socketId, payload); } }
public async Task RegisterDataConnection(WebSocket socket, Guid cid, string path) { if (!Guid.TryParse(path.TrimStart('/'), out var reqCID)) { return; } if (!reqDConnections.TryRemove(reqCID, out var reqConnInfo)) { return; } if (!mConnections.TryGetValue(reqConnInfo.mainConnectionId, out var mainConnection)) { return; } var dConn = new DataConnectionInfo { type = ConnectionType.Data, connectionId = cid, socket = socket, aes = reqConnInfo.aes, bufferSize = reqConnInfo.blockSize, mainConnectionId = mainConnection.connectionId }; if (!dConnections.TryAdd(cid, dConn)) { return; } mainConnection.dataConnections.TryAdd(cid, cid); await ProcessingDataConnection(dConn); mainConnection.dataConnections.TryRemove(cid, out _); }