public override void Read(IChannelHandlerContext ctx, object input) { var frame = input as WebSocketFrame; if (frame != null) { if (frame.Type == WebSocketFrameType.Ping) { ctx.Write(new WebSocketFrame { Type = WebSocketFrameType.Pong, IsFinal = true }); } else if (frame.Type == WebSocketFrameType.Close) { ctx.Write( new WebSocketFrame { Type = WebSocketFrameType.Close, IsFinal = true, Bytes = Encoding.UTF8.GetBytes("1000") } ); } else if (frame.Type == WebSocketFrameType.Text) { string inboundMessage = frame.Text; string echo = string.Format("Ваше сообщение: '{0}'", inboundMessage); ctx.Write( new WebSocketFrame { Type = WebSocketFrameType.Text, IsFinal = true, Bytes = Encoding.UTF8.GetBytes(echo) } ); } } }
public sealed override void Write(IChannelHandlerContext ctx, object message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } T messageObj = message as T; if (message == null) { throw new ArgumentException($"Message is not {typeof(T)}."); } // Пока объект кодируется в буфер, продолжаем отправлять буферы дальше по конвейеру. bool continueEncoding; do { ByteBuf byteBuf = Encode(ctx, messageObj, out continueEncoding); ctx.Write(byteBuf); }while (continueEncoding); }
public virtual void Write(IChannelHandlerContext ctx, object message) { ctx.Write(message); }
protected override void Read(IChannelHandlerContext ctx, ByteBuf byteBuf) { if (byteBuf.ReadableBytes() > 0) { if (_httpMatcher == null) { _httpMatcher = new HttpMatcher(); } bool continueMatching; _httpMatcher.Match(byteBuf, out continueMatching); if (continueMatching) { // Как минимум мы можем освободить прочитанную часть. byteBuf.ReleaseReaded(); return; } // TODO: если будет реализован проброс, то буфер освобождать нельзя, а надо будет просто сделать возврат в начало чтения. // Освобождаем буфер, т.к. больше матчить не будем. byteBuf.Release(); HttpMatchState state = _httpMatcher.GetMatchingState; bool handshake = HandshakeMatched(state); if (handshake) { ByteBuf outByteBuf = SwitchingProtocolResponse.Get(ctx, state.SecWebSocketKey, state.SecWebSocketKeyLen); _httpMatcher.Clear(); // TODO: !!!! временное решение !!!! Task writeTask = Task.Factory.StartNew( () => { ctx.Write(outByteBuf); } ); Task transformationTask = writeTask.ContinueWith( (writeTaskArg) => { if (writeTask.IsCompleted) { ctx.Pipeline.AddBefore( ctx.Name, _webSocketsMiddlewareName + "Encoder", _webSocket13EncoderProvider ); ctx.Pipeline.Replace( ctx.Name, _webSocketsMiddlewareName + "Decoder", _webSocket13DecoderProvider ); } } ); transformationTask.Wait(); } else { // TODO: проброс или bad response _httpMatcher.Clear(); } } }