public abstract SendAsync ( System |
||
buffer | System |
|
messageType | System | |
endOfMessage | bool | |
cancellationToken | System | |
Résultat | System.Threading.Tasks.Task |
/// <summary> /// Skips the message queue and directly sends over the Websocket. /// </summary> /// <param name="bytes"></param> /// <param name="ct"></param> /// <returns></returns> public async Task <SendResult> SendAsync(byte[] bytes, CancellationToken ct) { if (_ws.State != WebSocketState.Open) { TraceEvent( $"(SendAsync) Invalid attempt to send while socket is not open", EventIdentifiers.WS_ERR_SEND_SOCK_CLOSE, TraceEventType.Error ); throw new InvalidOperationException("Websocket is not open"); } TraceEvent($"(SendAsync) Queued bytes [ len: {bytes.Length} ]", EventIdentifiers.WS_VER_QMSG_ASYNC, TraceEventType.Verbose); ArraySegment <byte> buf = new ArraySegment <byte>(bytes); await _sem.WaitAsync(ct); if (ct.IsCancellationRequested) { _sem.Release(); TraceEvent($"(SendAsync) Operation cancelled", EventIdentifiers.WS_WAR_CANC_SEND, TraceEventType.Warning); ct.ThrowIfCancellationRequested(); } await _ws.SendAsync(new ArraySegment <byte>(bytes, 0, bytes.Length), _msgType, true, ct); return(SendResult.Sent); }
/// <summary> /// Use this function to send a buffer over the network. This method blocks until all data in buffer is sent or until underlying socket receive time out. /// </summary> /// <param name="data">Data to be written to the network.</param> /// <returns>Returns the amount of bytes sent.</returns> public int Send(byte[] data) { ArraySegment <byte> buffer = new ArraySegment <byte>(data); Task.WaitAll(socket.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None)); return(data.Length); //There is no other way }
public async void OnEvenAdded(object sender, Event @event) { _logger.LogInformation("Event add received, going to notify Web Socket"); var sent = JsonSerializer.SerializeToUtf8Bytes(new WebSocketResponse("event", new Dictionary <string, object> { [sender.ToString()] = @event }), _options); await _socket.SendAsync(sent, WebSocketMessageType.Text, true, _cancellation) .ConfigureAwait(false); }
private static Task SendStringAsync(System.Net.WebSockets.WebSocket socket, string data, CancellationToken ct = default(CancellationToken)) { var buffer = Encoding.UTF8.GetBytes(data); var segment = new ArraySegment <byte>(buffer, 0, buffer.Length); return(socket.SendAsync(segment, WebSocketMessageType.Text, true, ct)); }
public async Task EchoAsync(WebSocket webSocket) { var buffer = new ArraySegment<byte>(new byte[8192]); for (; ;) { var result = await webSocket.ReceiveAsync( buffer, CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { return; } else if (result.MessageType == WebSocketMessageType.Text) { Console.WriteLine("{0}", System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count)); } await webSocket.SendAsync( new ArraySegment<byte>(buffer.Array, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); } }
public static async Task SendMessage(ArraySegment <byte> data, System.Net.WebSockets.WebSocket webSocket) { await webSocket.SendAsync(data, WebSocketMessageType.Text, endOfMessage : true, cancellationToken : CancellationToken.None); }
public Task ExecuteAsync(System.Net.WebSockets.WebSocket socket, Thing thing, JsonElement data, JsonSerializerOptions options, IServiceProvider provider, CancellationToken cancellationToken) { foreach (var(actionName, actionContext) in thing.ThingContext.Actions) { if (!data.TryGetProperty(actionName, out var json)) { continue; } _logger.LogTrace("{actionName} Action found. [Name: {thingName}]", actionName, thing.Name); var actionInfo = (ActionInfo)JsonSerializer.Deserialize(json.GetRawText(), actionContext.ActionType, options); if (!actionInfo.IsValid()) { _logger.LogInformation("{actionName} Action has invalid parameters. [Name: {thingName}]", actionName, thing.Name); socket.SendAsync(s_errorMessage, WebSocketMessageType.Text, true, cancellationToken) .ConfigureAwait(false); continue; } _logger.LogInformation("Going to execute {actionName} action. [Name: {thingName}]", actionName, thing.Name); var namePolicy = options.PropertyNamingPolicy; actionInfo.Href = $"/things/{namePolicy.ConvertName(thing.Name)}/actions/{namePolicy.ConvertName(actionName)}/{actionInfo.Id}"; thing.ThingContext.Actions[actionInfo.GetActionName()].Actions.Add(actionInfo.Id, actionInfo); actionInfo.ExecuteAsync(thing, provider) .ConfigureAwait(false); } return(Task.CompletedTask); }
/// <inheritdoc/> public async ValueTask ExecuteAsync(System.Net.WebSockets.WebSocket socket, Thing thing, object data, IServiceProvider provider, CancellationToken cancellationToken) { var logger = provider.GetRequiredService <ILogger <AddEventSubscription> >(); var convert = provider.GetRequiredService <IJsonConvert>(); foreach (var(eventName, _) in convert.ToEnumerable(data)) { if (thing.ThingContext.Events.TryGetValue(eventName, out _)) { logger.LogInformation("Going to add subscribes socket to event. [Thing: {thing}][Event: {eventName}]", thing.Name, eventName); thing.ThingContext.EventsSubscribes[eventName] .TryAdd( thing.ThingContext.Sockets.First(x => x.Value == socket).Key, socket); } else { logger.LogInformation("Event not found. [Thing: {thing}][Event: {eventName}]", thing.Name, eventName); await socket.SendAsync(s_errorActionNotFound, WebSocketMessageType.Text, true, cancellationToken) .ConfigureAwait(false); } } }
private async Task SendAsync(ArraySegment <byte> message, WebSocketMessageType messageType, bool endOfMessage = true) { if (_webSocket.State != WebSocketState.Open) { return; } try { await _webSocket.SendAsync(message, messageType, endOfMessage, CancellationToken.None); } catch (Exception ex) { Trace.TraceError("Error Sending : " + ex.Message); } }
private static async Task SendMessage(WebSocket webSocket, string msg, bool endOfMessage) { logger.LogVerbose("SendMessage = {0}", msg); var msgBytes = Encoding.UTF8.GetBytes(msg); await webSocket.SendAsync(new ArraySegment<byte>(msgBytes, 0, msgBytes.Length), WebSocketMessageType.Text, endOfMessage, CancellationToken.None); }
protected override async Task Send(IEnumerable <ArraySegment <byte> > segments, CancellationToken ct) { foreach (var segment in segments) { await _webSocket.SendAsync(segment, WebSocketMessageType.Binary, true, ct) .ConfigureAwait(false); } }
/// <summary> /// 发送消息 /// </summary> /// <param name="message"></param> /// <returns></returns> public async Task SendMessageAsync(string message) { System.Net.WebSockets.WebSocket webSocket = HttpListenerWebSocketContext.WebSocket; var bytes = Encoding.GetBytes(message); Console.WriteLine($"{ID}发送消息:{message}"); await webSocket.SendAsync(new ArraySegment <byte>(bytes), WebSocketMessageType.Binary, true, cancellationToken); }
public async Task SendBytesAsync(System.Net.WebSockets.WebSocket websocket, byte[] data, CancellationToken cancellationToken) { if (websocket.CloseStatus == null) { ArraySegment <byte> buffer = new ArraySegment <byte>(data); await websocket.SendAsync(buffer, WebSocketMessageType.Text, true, cancellationToken); } }
private async Task Send(WebSocket webSocket, SocketMessage message) { if (webSocket != null && webSocket.State == WebSocketState.Open) { var value = new ArraySegment<byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message))); await webSocket.SendAsync(value, WebSocketMessageType.Text, true, CancellationToken.None); } }
private async Task SendAsync(GatewayOpCode opCode, object payload) { var frame = new SocketFrame { Operation = (int)opCode, Payload = payload }; var bytes = _server.Serialize(frame, _outBuffer); var segment = new ArraySegment <byte>(_outBuffer, 0, bytes); await _socket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None).ConfigureAwait(false); }
public void SendMessage(System.Net.WebSockets.WebSocket socket, string message) { if (socket.State != WebSocketState.Open) { return; } byte[] sendBuffer = Encoding.UTF8.GetBytes(message); socket.SendAsync(new ArraySegment <byte>(sendBuffer), WebSocketMessageType.Text, endOfMessage: true, cancellationToken: CancellationToken.None); }
/// <summary> /// 发送数据 /// </summary> /// <param name="data">数据</param> /// <param name="endMessage">是否末尾数据</param> async Task IWebSocket.SendAsync(SocketResult data, bool?endMessage) { ArraySegment <byte> arg = new ArraySegment <byte>( UTF8Encoding.Default.GetBytes( JsonConvert.SerializeObject(data) ) ); await m_socket.SendAsync(arg, WebSocketMessageType.Text, endMessage.GetValueOrDefault(true), CancellationToken.None); }
public Task Send(ArraySegment <byte> data, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancelToken) { var sendContext = new NetSendContext(data, endOfMessage, messageType, cancelToken); return(_sendQueue.Enqueue( async s => { await _webSocket.SendAsync(s.Buffer, s.MessageType, s.EndOfMessage, s.CancellationToken); }, sendContext)); }
public async Task <bool> SendItemAsync <T>(T command, System.Net.WebSockets.WebSocket socket, CancellationToken token) { var buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(command)); using (_Logger.BeginScope($"Sending message from socket with state {socket.State}", socket)) { await socket.SendAsync(new ArraySegment <byte>(buffer), WebSocketMessageType.Text, true, token); } return(true); }
public async Task SendMessageAsync(System.Net.WebSockets.WebSocket socket, string message) { if (socket.State != WebSocketState.Open) { return; } await socket.SendAsync(new ArraySegment <byte>(Encoding.ASCII.GetBytes(message), 0, message.Length), WebSocketMessageType.Text, true, CancellationToken.None); }
public async Task <bool> SendMessageAsync(string message, System.Net.WebSockets.WebSocket socket, CancellationToken token) { var buffer = Encoding.UTF8.GetBytes(message); using (_Logger.BeginScope($"Sending message from socket with state {socket.State}", socket)) { await socket.SendAsync(new ArraySegment <byte>(buffer), WebSocketMessageType.Text, true, token); } return(true); }
public static async Task CallClientMethod(string command) { if (!_isInitialized) { return; } var buffer = Encoding.UTF8.GetBytes(command); await _webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None); }
public static async Task ExecuteAPI(HttpContext context, System.Net.WebSockets.WebSocket webSocket) { var buffer = new byte[1024 * 20]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { string strRequest = Encoding.UTF8.GetString(buffer); string str = strRequest.Replace("\0", string.Empty); string jsonStr = string.Empty; try { //Method APIModel apiModel = JsonSerializer.Deserialize <APIModel>(str); string apiName = apiModel.Method; BaseCommand command = Activator.CreateInstance(CommandsDict[apiName]) as BaseCommand; command.WebSocket = webSocket; jsonStr = command.Execute(str); buffer = Encoding.UTF8.GetBytes(jsonStr); BaseRequestModel requestModel = JsonSerializer.Deserialize <BaseRequestModel>(str); if (!string.IsNullOrEmpty(requestModel.Token)) { if (command is UserLogoutCommand) { //do nothing } else { UserInfo userInfo = UserInfoDict[requestModel.Token]; userInfo.ActionTime = DateTime.Now; } } else if (command is UserLoginCommand) { //do nothing } } catch (Exception ex) { ErrorResponseModel responseModel = new ErrorResponseModel(); responseModel.StatusCode = 0; responseModel.ErrorCode = "500"; responseModel.Message = ex.Message; jsonStr = JsonSerializer.Serialize(responseModel); buffer = Encoding.UTF8.GetBytes(jsonStr); } await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, jsonStr.Length), result.MessageType, result.EndOfMessage, CancellationToken.None); buffer = new byte[1024 * 20]; result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); }
static async Task SendAsync(WebSocket ws, Message m) { using (MemoryStream mem = new MemoryStream()) using (StreamWriter sw = new StreamWriter(mem)) { await sw.WriteAsync(JsonConvert.SerializeObject(m)); await sw.FlushAsync(); var seg = new ArraySegment<byte>(mem.GetBuffer(), 0, (int)mem.Length); await ws.SendAsync(seg, WebSocketMessageType.Text, true, CancellationToken.None); } }
private async Task Echo(WebSocket webSocket) { byte[] buffer = new byte[1024 * 4]; var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); }
public async Task Send(DMessage message, bool flush = true) { var buffer = await _messageEncoder.EncodeAsync(message, _gzip); if (_webSocket == null || _webSocket.State != WebSocketState.Open) { throw ErrorCodes.SystemError.CodeException($"WebSocket连接已关闭"); } await _webSocket.SendAsync(new ReadOnlyMemory <byte>(buffer), WebSocketMessageType.Binary, flush, CancellationToken.None); }
/// <inheritdoc/> public async ValueTask ExecuteAsync(System.Net.WebSockets.WebSocket socket, Thing thing, object data, IServiceProvider provider, CancellationToken cancellationToken) { var option = provider.GetRequiredService <ThingOption>(); var convert = provider.GetRequiredService <IJsonConvert>(); foreach (var(actionName, value) in convert.ToEnumerable(data)) { if (!thing.ThingContext.Actions.TryGetValue(actionName, out var actions)) { _logger.LogInformation("Action not found. [Thing: {name}][Action: {actionName}]", thing.Name, actionName); await socket.SendAsync(s_errorActionNotFound, WebSocketMessageType.Text, true, cancellationToken) .ConfigureAwait(false); continue; } if (!actions.TryAdd(value, out var action)) { _logger.LogInformation("Action has invalid parameters. [Thing: {name}][Action: {actionName}]", thing.Name, actionName); await socket.SendAsync(s_errorInvalidParameter, WebSocketMessageType.Text, true, cancellationToken) .ConfigureAwait(false); continue; } action.Thing = thing; var namePolicy = option.PropertyNamingPolicy; action.Href = $"/things/{namePolicy.ConvertName(thing.Name)}/actions/{namePolicy.ConvertName(actionName)}/{action.GetId()}"; _logger.LogInformation("Going to execute action. [Thing: {name}][Action: {actionName}][Action Id: {actionId}]", thing.Name, actionName, action.GetId()); _ = action.ExecuteAsync(thing, provider).ConfigureAwait(false); } }
private static async Task Echo(HttpContext context, System.Net.WebSockets.WebSocket webSocket) { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); }
public Task ExecuteAsync(System.Net.WebSockets.WebSocket socket, Thing thing, JsonElement data, JsonSerializerOptions options, IServiceProvider provider, CancellationToken cancellationToken) { foreach (var propertyName in thing.ThingContext.Properties.PropertiesNames) { if (!data.TryGetProperty(options.PropertyNamingPolicy.ConvertName(propertyName), out var property)) { continue; } var result = thing.ThingContext.Properties.SetProperty(propertyName, property); if (result == SetPropertyResult.InvalidValue) { _logger.LogInformation("Invalid property value. [Thing: {thing}][Property Name: {propertyName}]", thing.Name, propertyName); var response = JsonSerializer.SerializeToUtf8Bytes( new WebSocketResponse("error", new ErrorResponse("400 Bad Request", "Invalid property value")), options); socket.SendAsync(response, WebSocketMessageType.Text, true, cancellationToken) .ConfigureAwait(false); } if (result == SetPropertyResult.ReadOnly) { _logger.LogInformation("Read-only property. [Thing: {thing}][Property Name: {propertyName}]", thing.Name, propertyName); var response = JsonSerializer.SerializeToUtf8Bytes( new WebSocketResponse("error", new ErrorResponse("400 Bad Request", "Read-only property")), options); socket.SendAsync(response, WebSocketMessageType.Text, true, cancellationToken) .ConfigureAwait(false); } } return(Task.CompletedTask); }
public async Task SendMessageAsync(System.Net.WebSockets.WebSocket socket, string message) { if (socket.State != WebSocketState.Open) { return; } await socket.SendAsync(buffer : new ArraySegment <byte>(array: Encoding.ASCII.GetBytes(message), offset: 0, count: message.Length), messageType : WebSocketMessageType.Text, endOfMessage : true, cancellationToken : CancellationToken.None); }
/// <summary> /// 发送消息 /// </summary> /// <param name="message">消息内容</param> /// <param name="webSocketMessageType">消息类型 默认为文本</param> /// <param name="webSocket"></param> internal static async Task SendMessage(this System.Net.WebSockets.WebSocket webSocket, WebSocketMessageModel sendMessageModel, WebSocketMessageType webSocketMessageType = WebSocketMessageType.Text) { //验证连接是否正常 if (webSocket.State != WebSocketState.Open) { return; } if (sendMessageModel.IsNull()) { return; } //发送 await webSocket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(await sendMessageModel.ToJsonAsync())), webSocketMessageType, true, CancellationToken.None); }
private async Task EchoWebSocket(WebSocket webSocket) { byte[] buffer = new byte[1024]; WebSocketReceiveResult received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!webSocket.CloseStatus.HasValue) { // Echo anything we receive await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, received.Count), received.MessageType, received.EndOfMessage, CancellationToken.None); received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, CancellationToken.None); }
public async Task SendMessageAsync <T>(System.Net.WebSockets.WebSocket socket, T message) { try { if (socket.State != WebSocketState.Open) { return; } var msg = JsonConvert.SerializeObject(message); await socket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(msg)), WebSocketMessageType.Text, true, CancellationToken.None); } catch { // ignored } }
/// <summary> /// Send data to the client through the member context from the server. /// </summary> /// <param name="data">The data received from the server.</param> private async void SentFromServerEx(byte[] data) { if (_webSocket != null) { try { // Reset the initial timeout time. _initialTimeOutTime = DateTime.Now; // Send data back to the client. await _webSocket.SendAsync(new ArraySegment <byte>(data, 0, _receiveResult.Count), WebSocketMessageType.Binary, _receiveResult.EndOfMessage, CancellationToken.None); } catch (Exception ex) { _lastError = ex; } } }
/// <summary> /// 发送消息 /// </summary> /// <param name="message">文字消息</param> /// <returns></returns> public async Task SendMessage(string message) { var data = new { content = message, time = DateTimeOffset.Now.DateTime.ToString() }; var newString = Newtonsoft.Json.JsonConvert.SerializeObject(data); //String.Format("Hello, " + receiveString + " ! Time {0}", DateTimeOffset.Now.ToString()); Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(newString); await _webSocket.SendAsync(new ArraySegment <byte>(bytes), WebSocketMessageType.Text, true, _cancellationToken).ConfigureAwait(false); }
/// <summary> /// /// </summary> /// <param name="webSocket"></param> /// <returns></returns> public async Task ConnectClientAsync(System.Net.WebSockets.WebSocket webSocket) { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { string content = Encoding.UTF8.GetString(buffer); await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); }
public async void Execute(HttpListenerContext context, EventSocketExecuteResult callback){ WebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null); _ws = webSocketContext.WebSocket; for (int i = 0; i != 10; ++i) { // await Task.Delay(20); var time = DateTime.Now.ToLongTimeString(); var buffer = Encoding.UTF8.GetBytes(time); var segment = new ArraySegment<byte>(buffer); await _ws.SendAsync(segment, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None); } if (callback!=null) { callback (true); } // await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None); }
private static async Task DoWebSocketReceiveSendAsync(WebSocket receiver, WebSocket sender, CancellationToken ct) { if (receiver == null || sender == null) { return; } ArraySegment<byte> receiveBuffer = new ArraySegment<byte>(new byte[65335]); while (receiver.State == WebSocketState.Open && sender.State == WebSocketState.Open) { if (ct.IsCancellationRequested) { receiver.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", CancellationToken.None).SilenceException<WebSocketException>().DoNotWait(); sender.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", CancellationToken.None).SilenceException<WebSocketException>().DoNotWait(); return; } WebSocketReceiveResult result = await receiver.ReceiveAsync(receiveBuffer, ct); byte[] data = await receiveBuffer.ToByteArrayAsync(result.Count); ArraySegment<byte> sendBuffer = new ArraySegment<byte>(data); await sender.SendAsync(sendBuffer, result.MessageType, result.EndOfMessage, ct); if (result.MessageType == WebSocketMessageType.Close) { await receiver.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", ct); } } }
private async Task WriteSocket(WebSocket socket, object item) { var outputBuffer = new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes(Builder.Create(item))); await socket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.Token); }
private static WebSocketSendAsync WebSocketSendAsync(WebSocket webSocket) { return (buffer, messageType, endOfMessage, cancel) => webSocket.SendAsync(buffer, OpCodeToEnum(messageType), endOfMessage, cancel); }
private async Task CopyFromStreamToWebSocketWorker(Stream stream, WebSocket webSocket, CancellationToken ct) { var buffer = new byte[0x10000]; while (webSocket.State == WebSocketState.Open) { ct.ThrowIfCancellationRequested(); Log("TCP -> WS: waiting for packet."); int count = await stream.ReadAsync(buffer, 0, buffer.Length, ct); Log("TCP -> WS: received packet:\n{0}", Encoding.UTF8.GetString(buffer, 0, count)); if (count == 0) { Log("TCP -> WS: zero-length TCP packet received, connection closed."); break; } await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, count), WebSocketMessageType.Binary, true, ct); Log("TCP -> WS: packet relayed."); } }
private static async Task PipeToWebSocketWorker(WebSocket socket, IMessagePipeEnd pipe, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); byte[] message; try { message = await pipe.ReadAsync(cancellationToken); } catch (PipeDisconnectedException) { break; } await socket.SendAsync(new ArraySegment<byte>(message, 0, message.Length), WebSocketMessageType.Binary, true, cancellationToken); } }
private async static Task SendTextMessage(WebSocket socket, string textMessage) { ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(textMessage)); await socket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None); }
private static Task SendMessageAsync(string message, WebSocket socket, CancellationToken cancel) { var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)); return socket.SendAsync(buffer, WebSocketMessageType.Text, true, cancel); }
private async static Task SendBinaryMessage(WebSocket socket, byte[] binaryMessage) { ArraySegment<byte> outputBuffer = new ArraySegment<byte>(binaryMessage); await socket.SendAsync(outputBuffer, WebSocketMessageType.Binary, true, CancellationToken.None); }
private static async Task SendMessage(WebSocket webSocket, string message) { var msgBytes = Encoding.UTF8.GetBytes(message); try { await webSocket.SendAsync(new ArraySegment<byte>(msgBytes, 0, msgBytes.Length), WebSocketMessageType.Text, true, CancellationToken.None); } catch (Exception ex) { logger.LogVerbose("Exception in SendMessage: {0}", ex.Message); } }