public async Task <RocketResult> ReceiveStreamAsync(MemoryStream stream, CancellationToken token) { var result = new RocketResult(); try { await mReceiveLock.WaitAsync(token); stream.Seek(0, SeekOrigin.Begin); var buffer = new ArraySegment <byte>(new byte[8192]); IWebSocketReceiveResult socketResult = null; do { socketResult = await mSocket.ReceiveAsync(buffer, token); if (socketResult.MessageType == WebSocketMessageType.Close) { await mSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "normal closure", token); return(result.SetClosed()); } stream.Write(buffer.Array, buffer.Offset, socketResult.Count); } while (!socketResult.EndOfMessage); stream.Seek(0, SeekOrigin.Begin); return(result); } catch (WebSocketException ex) { return(result.SetException(ex) .SetClosed()); } finally { try { mReceiveLock.Release(); } catch (SemaphoreFullException) { } } }
/// <inheritdoc /> protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { foreach (var ws in WebSockets.Where(ws => ws != context)) { Send(ws, rxBuffer.ToText()); } }
/// <inheritdoc /> protected override Task OnMessageReceivedAsync( IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { return(Task.CompletedTask); //return SendToOthersAsync(context, Encoding.GetString(buffer)); }
/// <inheritdoc /> protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { lock (_syncRoot) { var arg = rxBuffer.ToText(); _processes[context].StandardInput.WriteLine(arg); } }
/// <inheritdoc /> protected override Task OnMessageReceivedAsync( IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { SendToOthersAsync(context, Encoding.GetString(rxBuffer)); return(null); }
protected override Task OnMessageReceivedAsync( IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { //using var request = _serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope(); //var file = request.ServiceProvider.GetService<IFilesHandler>(); //return SendToOthersAsync(context, Encoding.GetString(rxBuffer)); return(Task.CompletedTask); }
private static async Task WebSocketEcho(IWebSocketContext webSocketContext) { var buffer = new byte[1024]; IWebSocketReceiveResult received = await webSocketContext.Receive(new ArraySegment <byte>(buffer)); while (!webSocketContext.ClientClosed) { await webSocketContext.Send( new ArraySegment <byte>(buffer, 0, received.Count), received.MessageType, received.EndOfMessage); received = await webSocketContext.Receive(new ArraySegment <byte>(buffer)); } await webSocketContext.Close(); }
private static async Task WebSocketReverseMessage(IWebSocketContext webSocketContext) { var buffer = new byte[1024]; IWebSocketReceiveResult received = await webSocketContext.Receive(new ArraySegment <byte>(buffer)); while (!webSocketContext.ClientClosed) { byte[] reversedMessage = Encoding.UTF8.GetBytes(String.Concat(Encoding.UTF8.GetString(buffer, 0, received.Count).Reverse())); await webSocketContext.Send( new ArraySegment <byte>(reversedMessage, 0, reversedMessage.Length), received.MessageType, received.EndOfMessage); received = await webSocketContext.Receive(new ArraySegment <byte>(buffer)); } await webSocketContext.Close(); }
private static async Task WebSocketCheckEnv(IWebSocketContext webSocketContext) { var buffer = new byte[1024]; IWebSocketReceiveResult received = await webSocketContext.Receive(new ArraySegment <byte>(buffer)); while (!webSocketContext.ClientClosed) { bool haveEnv = webSocketContext.Environment != null; byte[] bytes = Encoding.UTF8.GetBytes(haveEnv.ToString()); await webSocketContext.Send( new ArraySegment <byte>(bytes, 0, bytes.Length), received.MessageType, received.EndOfMessage); received = await webSocketContext.Receive(new ArraySegment <byte>(buffer)); } await webSocketContext.Close(); }
/// <inheritdoc /> protected override async Task OnMessageReceivedAsync(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { string text = Encoding.GetString(rxBuffer); JsEvent evt = JsonUtils.DeserializeFromJson <JsEvent>(text); Logger.Info("Got message of type {0}", evt.Type); if (evt.Type == "spam") { // wait some time, simulating actual work being done and then respond with a big chunk of text Random rnd = new Random(); await Task.Delay(rnd.Next(50, 150)); var responseEvent = new JsEvent("spam-back") { Data = JsDataRow.GenerateLargeTable() }; await SendTargetedEvent(context, responseEvent).ConfigureAwait(false); } }
/// <inheritdoc /> protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { if (!this.DetourClients.TryGetValue(context.Id, out DetourClient client)) { return(null); } string message = Encoding.UTF8.GetString(rxBuffer); Console.WriteLine($"[{Enum.GetName(typeof(ClientTypeEnum), this.ClientType)}] -> {message}."); client.WebSocket.Send(message); this._formRef.AddMessageToDataGridView(this.ClientType, message); if (message.Contains("disconnecting")) { this.SendAsync(context, "4\"primus::server::close\""); client.WebSocket.Close(); this.CloseAsync(context); this.DetourClients.TryRemove(context.Id, out DetourClient removedClient); } if (message.StartsWith("4{") && message.Contains("sendMessage")) { var messageObject = JsonConvert.DeserializeObject <JObject>(message.Substring(1, message.Length - 1)); if (messageObject.TryGetValue("data", out JToken data)) { ProtocolBuilderManager.BuildSendMessage(data.ToString()); } } return(Task.CompletedTask); }
protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { string message = System.Text.Encoding.UTF8.GetString(buffer); this._logger.Info($"Receive -> {message} from {context.Id}."); if (!this.Clients.ContainsKey(context.Id)) { return(null); } this.Clients.TryGetValue(context.Id, out Client client); //primus ping protocol if (message.StartsWith("2")) { SendAsync(context, "3"); this._logger.Info($"Sent -> pong primus protocol."); } FrameIntercepterManager.Intercept(client, message.Substring(1, message.Length - 1)); foreach (var messageInQueue in client.MessagesQueues) { this._logger.Info($"Sent -> {messageInQueue.Value} to {context.Id}."); SendAsync(context, messageInQueue.Value); } client.MessagesQueues.Clear(); return(Task.CompletedTask); }
protected override void OnMessageReceived(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { //TODO: Considering to send data from client side as binary Streamed JSON for performance in the future ! //TODO: Still, the mismatching CLR type namespace need to be fixed first //Value type reference as byte[] and/or string are not good for performance string methodProxyJson = buffer.ToText(); Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { MethodProxy taksInput = null; MethodProxy taksOutput = null; try { taksInput = ContextBridge.GetMethodProxyFromJSON(ref methodProxyJson); taksOutput = await ContextBridge.Receive(taksInput); } catch (Exception ex) { ConsoleHelper.WriteLine("Error: [Native] - BlazorContextBridge.Receive: " + ex.Message); } try { string jsonReturnValue = ContextBridge.GetJSONReturnValue(taksOutput); SendMessageToClient(jsonReturnValue); } catch (Exception ex) { ConsoleHelper.WriteLine("Error: [Native] - BlazorContextBridge.Send: " + ex.Message); } }); }
protected override void OnFrameReceived(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { }
protected override Task OnFrameReceivedAsync(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { return(Task.CompletedTask); }
protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { return(Task.CompletedTask); }
protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { var str = Encoding.GetString(buffer); Dictionary <string, object> watchedKeyValues; lock (_lockingObject) watchedKeyValues = watchedKeyValuesPerContext[context.Id]; lock (watchedKeyValues) { watchedKeyValues.Clear(); List <string> kvNames = null; try { kvNames = Newtonsoft.Json.JsonConvert.DeserializeObject <List <string> >(str); } catch (Exception ex) { ex.Log(context.Id); } if (kvNames != null && kvNames.Any()) { watchedKeyValues.Clear(); foreach (var key in kvNames) { if (!string.IsNullOrEmpty(key)) { watchedKeyValues[key] = null; } } } } return(Task.CompletedTask); }
protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { var user_id = context.HttpContextId; TripleDESCryptoServiceProvider crypto; UserProfile profile; if (API.TripleDES.UserDict.TryGetValue(user_id, out profile)) { // ---------------------------------------- crypto = profile.crypto; MsgRequest req = new MsgRequest(crypto, rxBuffer); if (req.MsgId != profile.next_msg_id) { return(Task.CompletedTask); } // ---------------------------------------- if (req.Type == "str") { string content = API.Encoding.ByteArrayToString(req.Data); if (API.Keyboard.EnableAutoTyping) { API.Keyboard.SendString(content); } if (API.Keyboard.EnableClipboard) { API.Keyboard.SetClipboard(content); } } // ---------------------------------------- string pongEncrypted = req.GetResponse(profile); SendToOthersAsync(context, req.GetRepeat(profile)); return(SendAsync(context, pongEncrypted)); } else { // ---------------------------------------- byte[] bytes = API.RSA.RSADecrypt(rxBuffer); if (bytes == null) { return(Task.CompletedTask); } string[] splitted = API.Encoding.ByteArrayToString(bytes).Split(';'); string type = splitted[0], key = splitted[1], iv = splitted[2]; // ---------------------------------------- if (type != "reg" || key.Length != 32 || iv.Length != 16) { return(Task.CompletedTask); } crypto = API.TripleDES.createDESCrypto(key, iv); string next_msg_id = API.Util.GetRandomHexString(4); string helloRaw = "acc;" + user_id + ";" + next_msg_id; string helloEncrypted = API.Util.StringToEncryptHex(helloRaw, crypto); API.TripleDES.UserDict.Add(user_id, new UserProfile() { userid = user_id, crypto = crypto, next_msg_id = next_msg_id }); return(SendAsync(context, helloEncrypted)); } }
/// <inheritdoc /> protected override void OnMessageReceived(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { //cumulus.LogDebugMessage("WS receive : " + buffer.ToString()); }
/// <summary> /// Called when this WebSockets Server receives a message frame regardless if the frame represents the EndOfMessage. /// </summary> /// <param name="context">The context.</param> /// <param name="buffer">The buffer.</param> /// <param name="result">The result.</param> protected abstract void OnFrameReceived( IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result);
protected override void OnFrameReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { // Do Nothing }
/// <inheritdoc /> protected override Task OnMessageReceivedAsync( IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) => SendToOthersAsync(context, Encoding.GetString(buffer));
protected override async Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { _logger.LogDebug($"Received {buffer.Length} bytes."); _logger.LogDebug(System.Text.Encoding.UTF8.GetString(buffer)); _logger.LogDebug(string.Join(" ", buffer.Select(d => d.ToString("X")))); if (buffer.Length < 1) { return; } var type = buffer[0]; switch (type) { case PacketAuthenticate: { if (context.Items.ContainsKey("user")) { return; } var token = System.Text.Encoding.UTF8.GetString(buffer, 1, buffer.Length - 1); if (string.IsNullOrEmpty(token)) { _logger.LogDebug($"Closing socket.Invalid token: {token}."); await CloseAsync(context); return; } var user = await _authenticationService.AuthenticateAsync(token); if (user == null) { _logger.LogDebug("Closing socket. User could not authenticate."); await CloseAsync(context); return; } if (await _permissionChecker.CheckPermissionAsync(user, PermissionAccessConsole) != PermissionGrantResult.Grant) { _logger.LogDebug("Closing socket. User does not have permission."); var msg = SerializeMessage(PacketMessage, new LogMessageDto { Message = $"Missing \"OpenMod.WebServer:{PermissionAccessConsole}\" permission to access console." }); await SendAsync(context, msg); await CloseAsync(context); return; } var canReadLogs = false; // await _permissionChecker.CheckPermissionAsync(user, PermissionAccessLogs) == PermissionGrantResult.Grant; context.Items.Add("user", canReadLogs ? user : new WebConsoleUser(user, context, this)); context.Items.Add("canReadLogs", canReadLogs); _logger.LogDebug($"User accepted: {user.FullActorName} (canReadLogs: {canReadLogs})"); break; } case PacketMessage: { if (!context.Items.ContainsKey("user")) { _logger.LogDebug("Closing socket. User not authenticated."); await CloseAsync(context); return; } var user = (IUser)context.Items["user"]; var message = System.Text.Encoding.UTF8.GetString(buffer, 1, buffer.Length - 1); var args = ArgumentsParser.ParseArguments(message); await _commandExecutor.ExecuteAsync(user, args, string.Empty); break; } } }
/// <inheritdoc /> protected override void OnFrameReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { // don't process partial frames }
protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { // placeholder }
protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result) { try { var req = JsonSerializer.Deserialize <WebsocketRequest>(buffer); if (req.RequestPayload.Equals("ping")) { return(SendAsync(context, new WebsocketResponse() { ResponseCode = 200, ResponsePayload = "pong" }.ToJson())); } else if (req.RequestPayload.Equals("cputemp")) { var cpuTemps = CpuTempMonitor.GetCpuTemps(); return(SendAsync(context, new WebsocketResponse() { ResponseCode = 200, ResponsePayload = cpuTemps }.ToJson())); } } catch (Exception e) { $"Exception - {e.Message}".Error(); } return(SendAsync(context, new WebsocketResponse() { ResponseCode = 400, ResponsePayload = "invalid request" }.ToJson())); }
/// <inheritdoc /> protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) => _processes.TryGetValue(context, out var process) ? process.StandardInput.WriteLineAsync(Encoding.GetString(rxBuffer)) : Task.CompletedTask;
protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { var text = System.Text.Encoding.UTF8.GetString(rxBuffer); logger.Trace($"OnMessageReceived():text={text}"); if (this.channelByWebSocketContext.TryGetValue(context, out EmbedIOSubscriptionApiConnection embedIOChannel)) { try { embedIOChannel.ReceiveMessageAsync(text).Wait(); } catch (Exception e) { logger.Trace(e); embedIOChannel.Dispose(); } } }
protected override async Task OnMessageReceivedAsync(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { await Task.CompletedTask; }
protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult) { //Effectively an echo server, anything one client sends gets sent to all connections. This allows other 'bots' to potentially interact and publish their own events. foreach (var ws in WebSockets) { if (ws != context) { Send(ws, rxBuffer.ToArray()); } } }