public PipelineFactory(ISocketChannel channel, MessageToMessageDecoder <IByteBuffer> decoder, MessageToMessageEncoder <string> encoder, ClientSession clientSession) { _channel = channel; _decoder = decoder; _encoder = encoder; _clientSession = clientSession; }
public DefaultSocketChannelConfiguration(ISocketChannel channel, Socket socket) : base(channel) { Contract.Requires(socket != null); this.Socket = socket; // Enable TCP_NODELAY by default if possible. socket.NoDelay = true; }
protected override void RaiseConnected(ISocketChannel channel) { base.RaiseConnected(channel); channel.BytesReceived += OnChannelBytesReceived; channel.Error += OnChannelError; this.channel = channel; }
protected virtual void RaiseConnected(ISocketChannel channel) { EventHandler <ChannelEventArgs> handler = Connected; if (handler != null) { handler(this, new ChannelEventArgs(channel)); } }
/// <summary> /// 发送数据处理 /// </summary> /// <param name="netChannel"></param> /// <param name="data"></param> public void SendData(NetChannel <TData> netChannel, object data) { ISocketChannel channel = netChannel.channel as ISocketChannel; if (channel != null) { channel.WriteAndFlushAsync(data); } }
/// <summary> /// 直接发送数据到网络 /// </summary> /// <param name="netChannel"></param> /// <param name="data"></param> public void SendData(NetChannel <TData> netChannel, byte[] data) { ISocketChannel channel = netChannel.channel as ISocketChannel; if (channel != null) { channel.SendData(data); } }
protected virtual void ChannelInit(ISocketChannel channel) { channel.Pipeline.AddLast(new LengthFieldPrepender(2)) .AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)) .AddLast(_decoder) .AddLast(_encoder) .AddLast(_resolver) .AddLast(_callbackResolver); }
public PipelineFactory(ISocketChannel channel, MessageToMessageDecoder <IByteBuffer> decoder, MessageToMessageEncoder <IEnumerable <IPacket> > encoder, ClientSession.ClientSession clientSession, ServerConfiguration configuration) { _channel = channel; _decoder = decoder; _encoder = encoder; _clientSession = clientSession; _configuration = configuration; }
protected override void InitChannel(ISocketChannel channel) { IChannelPipeline pipeline = channel.Pipeline; //pipeline.AddLast(new LoggingHandler("SRV-CONN")); pipeline.AddLast("framing-enc", new ProtobufVarint32LengthFieldPrepender()); pipeline.AddLast("framing-dec", new ProtobufVarint32FrameDecoder()); channel.Pipeline .AddLast("idle_timeout", new IdleStateHandler(READ_IDLE_TIMEOUT, WRITE_IDLE_TIMEOUT, 0)); base.InitChannel(channel); }
protected virtual void ChannelInit(ISocketChannel channel) { channel.Pipeline .AddLast(new IdleStateHandler(0, HeartbeatDelay / 1000, 0)) .AddLast(new ClientIdleHandler(SendHeartbeat)) .AddLast(new LengthFieldPrepender(2)) .AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)) .AddLast(_decoder) .AddLast(_encoder) .AddLast(_resolver) .AddLast(_callbackResolver); }
protected virtual void InitChannel(ISocketChannel channel) { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new LoggingHandler()); pipeline.AddLast("framing-enc", new MsgEncoder()); pipeline.AddLast("framing-dec", new MsgDecoder()); var handler = CreateConnection(); handler.connected += OnConnect; handler.disconnected += OnDisconnect; pipeline.AddLast("handler", handler); }
public DefaultSocketChannelConfiguration(ISocketChannel channel, Socket socket) : base(channel) { if (socket is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.socket); } Socket = socket; // Enable TCP_NODELAY by default if possible. try { TcpNoDelay = true; } catch { } }
internal void AddChannel(ISocketChannel channel) { _channels[channel.Id] = channel; var dmChannel = channel as SocketDMChannel; if (dmChannel != null) { _dmChannels[dmChannel.Recipient.Id] = dmChannel; } else { var groupChannel = channel as SocketGroupChannel; if (groupChannel != null) { _groupChannels.TryAdd(groupChannel.Id); } } }
static void Main(string[] args) { //ServerSocketChannel针对TCP服务端 ServerSocketChannel server = new ServerSocketChannel(); server.Hander(new MessageDecode()) //反序列化 .Hander(new MessageEcode()) //序列化 .Hander(new SimpleChannelRead()) //读取 .Option(SockOption.recBufSize, 100); //设置参数 Task <bool> r = server.BindAsync(7777, "127.0.0.1"); //SocketChannel针对TCP客户端或者UDP SocketChannel client = new SocketChannel(); ISocketChannel channel = client.InitChannel <TCPSocketChannel>(); client.Hander(new MessageDecode()) //反序列化 .Hander(new MessageEcode()) //序列化 .Hander(new SimpleChannelRead()) //读取 .Option(SockOption.recBufSize, 100); //设置参数 r = client.ConnectAsync("127.0.0.1", 7777); //UDP 服务端接收 SocketChannel udpServer = new SocketChannel(20); ISocketChannel udpChannel = udpServer.InitChannel <UDPSocketChannel>(); //必须先创建 udpServer.Hander(new MessageDecode()) //反序列化 .Hander(new MessageEcode()) //序列化 .Hander(new SimpleChannelRead()) //读取 .Option(SockOption.recBufSize, 100); //设置参数 r = udpServer.BindAsync(7777, "127.0.0.1"); //udp客户端 SocketChannel udpclient = new SocketChannel(); ISocketChannel udpchannel = udpclient.InitChannel <TCPSocketChannel>(); udpclient.Hander(new MessageDecode()) //反序列化 .Hander(new MessageEcode()) //序列化 .Hander(new SimpleChannelRead()) //读取 .Option(SockOption.recBufSize, 100); //设置参数 r = udpclient.ConnectAsync("127.0.0.1", 7777); }
public async Task ConnectAsync(Uri uri) { if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) { _channel = new SecureSocketChannel(); await _channel.ConnectAsync(uri.Host, uri.Port == 0? 443 : uri.Port); } else { _channel = new SocketChannel(); await _channel.ConnectAsync(uri.Host, uri.Port == 0? 443 : uri.Port); } _encodingContext = new EncodingContext(_channel); _encoder = new FrameEncoder(_encodingContext); Buffer.BlockCopy(ClientPreface, 0, _encodingContext.Buffer, _encodingContext.Offset, ClientPreface.Length); _encodingContext.Offset += ClientPreface.Length; var settingsFrame = new SettingsFrame(); await _encoder.EncodeAsync(settingsFrame); if (_encodingContext.ContainsData) { await _encodingContext.SendAsync(); } var ackOnOurFrame = await _decoder.DecodeAsync(_decodingContext) as SettingsFrame; if (ackOnOurFrame == null) { //TODO: Protocol error } var serverSettings = await _decoder.DecodeAsync(_decodingContext) as SettingsFrame; if (serverSettings == null) { //TODO: protocol error } }
public async Task ConnectAsync(Uri uri) { int port = uri.Port; if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) { _socket = new SecureSocketChannel(); if (port == 0) { port = uri.Port == 0 ? 443 : uri.Port; } } else { _socket = new SocketChannel(); if (port == 0) { port = uri.Port == 0 ? 80 : uri.Port; } } await _socket.ConnectAsync(uri.Host, port); _context = new EncodingContext(_socket); _encoder = new FrameEncoder(_context); var http2Settings = new SettingsFrame(); http2Settings.Encode(1, new EncodingContext()); var handshake = string.Format(@"GET / HTTP/1.1 Host: {0} Connection: Upgrade, HTTP2-Settings Upgrade: h2c HTTP2-Settings: {1} ", uri.Host, http2Settings); }
protected override void Configure(ISocketChannel ch) { var p = ch.Pipeline; switch (TestMode) { case TestMode.Intermediary: p.AddLast(new HttpServerCodec()); p.AddLast(new HttpObjectAggregator(1)); p.AddLast(new HttpIntermediaryHandler(this)); break; case TestMode.Terminal: p.AddLast(new HttpServerCodec()); p.AddLast(new HttpObjectAggregator(1)); p.AddLast(new HttpTerminalHandler(this)); break; case TestMode.Unresponsive: p.AddLast(UnresponsiveHandler.Instance); break; } }
//private HeartBeatMsg heartBeatMsg; public TcpConnection() { //GameWorld.Instance.OnApplicationQuit(Disconnect); new ServiceTask(new[] { typeof(IByteStorage), typeof(INetworkManager) }).Start().Continue(t => { _iNetworkManager = ServiceCenter.GetService <INetworkManager>(); _iSocketChannel = _iNetworkManager.Create("tcp") as ISocketChannel; _iSocketChannel.Setup(this); _iSocketChannel.OnChannelStateChange = OnServerStateChange; if (ServiceEventHandler != null) { ServiceEventHandler(); } // MsgHandler.Send((int)usercmd.MsgTypeCmd.Login, new usercmd.MsgLogin()); return(null); }); }
public ChannelEventArgs(ISocketChannel channel) { this.channel = channel; }
private Task OnChannelCreatedAsync(ISocketChannel channel) { MessageDispatcher.Dispatch(new ChannelCreatedNotification(channel)); return(Task.CompletedTask); }
private Task OnChannelUpdatedAsync(ISocketChannel oldChannel, ISocketChannel newChannel) { MessageDispatcher.Dispatch(new ChannelUpdatedNotification(oldChannel, newChannel)); return(Task.CompletedTask); }
public static void addGatewayChannel(string id, ISocketChannel gateway_channel) { map.AddOrUpdate(id, gateway_channel, (key, value) => value); }
public ICustomTcpChannelHandler GetNewWithChannelHandler(ISocketChannel socketChannel) { return(new LoginTcpHandler(socketChannel, UsefulContainer.Instance.Resolve <IPacketFactory>())); }
private void OnChannelBytesReceived(ISocketChannel socket, byte[] message) { RaiseBytesReceived(message); }
/// <summary> /// 解析数据并且传回 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="channel"></param> public static void AnalysisRequest <T>(NetChannel <T> channel) { // if (channel.recData == null) { return; } else { if (typeof(byte[]) == channel.recData.GetType()) { object data = channel.recData; byte[] req = (byte[])data; //说明是HTTP if (serviceHttp == null) { serviceHttp = new ServiceHttpProcessor(); } HttpRequest request = serviceHttp.ProcessRequestReturn(req); SrvRquest srvReq = null; object result = null; string json = null; if (request != null) { srvReq = CreateSrvReq(request); result = InvokeService(srvReq); } else { json = "解析HTTP错误,无法获取请求的参数或者服务名称"; } if (result != null) { json = StreamSerializer.JSONObjectToString <object>(result); } int streamLen = 1000; if (!string.IsNullOrEmpty(json)) { streamLen = json.Length * 2; } StreamBuffer stream = HTTPStream.GetInstance().GetStreamCompare(streamLen); serviceHttp.ProcessResult(json, request, stream.Buffer); stream.ResetSize((int)stream.Buffer.Length); stream.ResetPostion(); //重置位置; int len = stream.Size; //数据长度 byte[] tmp = null; ByteBuffer buffer = null; int position = 0; if (len < BufferManager.GetInstance().BufferSize) { //取出缓存Buffer buffer = BufferManager.GetInstance().GetBufferNum(1)[0]; tmp = buffer.buffer; position = buffer.Position; } else { tmp = new byte[len]; } ISocketChannel socket = channel.channel as ISocketChannel; if (socket != null) { stream.Buffer.Read(tmp, position, len); socket.SendData(tmp, position, len); socket.Close(); } if (buffer != null) { //释放取出的缓存 BufferManager.GetInstance().FreeBuffer(buffer); } HTTPStream.GetInstance().FreeBuffer(stream); } else { object data = channel.recData; SrvRquest req = (SrvRquest)data; object result = InvokeService(req); if (result != null) { ISocketClient <T> socket = channel.channel as ISocketClient <T>; if (socket != null) { socket.SendData(result); } socket.Close(); } } } }
protected virtual void RaiseConnected(ISocketChannel channel) { Connected?.Invoke(this, new ChannelEventArgs(channel)); }
protected override void OnChannelClosed(object o, EventArgs e) { channel = null; base.OnChannelClosed(o, e); }
public ClientChannel(string clientId, ISocketChannel channel) { ClientId = clientId; Channel = channel; }
/// <summary> /// Constructs a new <see cref="ChannelCreatedNotification"/> from the given values. /// </summary> /// <param name="channel">The value to use for <see cref="Channel"/>.</param> /// <exception cref="ArgumentNullException">Throws for <paramref name="channel"/>.</exception> public ChannelCreatedNotification(ISocketChannel channel) { Channel = channel ?? throw new ArgumentNullException(nameof(channel)); }
public EncodingContext(ISocketChannel channel) { _channel = channel; }
protected abstract void Configure(ISocketChannel ch);