List of usage examples for io.netty.channel ChannelHandlerContext executor
EventExecutor executor();
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java
License:Apache License
private void installSecurityToken(ChannelHandlerContext ctx, OpenSecureChannelResponse response) { ChannelSecurity.SecuritySecrets newKeys = null; if (response.getServerProtocolVersion().longValue() < PROTOCOL_VERSION) { throw new UaRuntimeException(StatusCodes.Bad_ProtocolVersionUnsupported, "server protocol version unsupported: " + response.getServerProtocolVersion()); }// www. j a v a2 s .c om ChannelSecurityToken newToken = response.getSecurityToken(); if (secureChannel.isSymmetricSigningEnabled()) { secureChannel.setRemoteNonce(response.getServerNonce()); newKeys = ChannelSecurity.generateKeyPair(secureChannel, secureChannel.getLocalNonce(), secureChannel.getRemoteNonce()); } ChannelSecurity oldSecrets = secureChannel.getChannelSecurity(); ChannelSecurity.SecuritySecrets oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null; ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null; secureChannel.setChannelSecurity(new ChannelSecurity(newKeys, newToken, oldKeys, oldToken)); DateTime createdAt = response.getSecurityToken().getCreatedAt(); long revisedLifetime = response.getSecurityToken().getRevisedLifetime().longValue(); if (revisedLifetime > 0) { long renewAt = (long) (revisedLifetime * 0.75); renewFuture = ctx.executor().schedule( () -> sendOpenSecureChannelRequest(ctx, SecurityTokenRequestType.Renew), renewAt, TimeUnit.MILLISECONDS); } else { logger.warn("Server revised secure channel lifetime to 0; renewal will not occur."); } ctx.executor().execute(() -> { // SecureChannel is ready; remove the acknowledge handler. if (ctx.pipeline().get(UaTcpClientAcknowledgeHandler.class) != null) { ctx.pipeline().remove(UaTcpClientAcknowledgeHandler.class); } }); ChannelSecurity channelSecurity = secureChannel.getChannelSecurity(); long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue(); long previousTokenId = channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L); logger.debug("SecureChannel id={}, currentTokenId={}, previousTokenId={}, lifetime={}ms, createdAt={}", secureChannel.getChannelId(), currentTokenId, previousTokenId, revisedLifetime, createdAt); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, UaRequestFuture message, ByteBuf out) throws Exception { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.buffer(); try {/* w w w. j av a 2s.co m*/ binaryEncoder.setBuffer(messageBuffer); binaryEncoder.encodeMessage(null, message.getRequest()); List<ByteBuf> chunks = chunkEncoder.encodeSymmetric(secureChannel, MessageType.SecureMessage, messageBuffer, requestId.getAndIncrement()); long requestId = chunkEncoder.getLastRequestId(); pending.put(requestId, message); // No matter how we complete, make sure the entry in pending is removed. // This covers the case where the request fails due to a timeout in the // upper layers as well as normal completion. message.getFuture().whenComplete((r, x) -> pending.remove(requestId)); ctx.executor().execute(() -> { chunks.forEach(c -> ctx.write(c, ctx.voidPromise())); ctx.flush(); }); } catch (UaException e) { logger.error("Error encoding {}: {}", message.getClass(), e.getMessage(), e); ctx.close(); } finally { messageBuffer.release(); } }); }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerHelloHandler.java
License:Apache License
private void onHello(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { logger.debug("[remote={}] Received Hello message.", ctx.channel().remoteAddress()); HelloMessage hello = TcpMessageDecoder.decodeHello(buffer); UaTcpStackServer server = socketServer.getServer(hello.getEndpointUrl()); if (server == null) { throw new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid, "unrecognized endpoint url: " + hello.getEndpointUrl()); }//from w w w .j a v a 2 s .co m ctx.channel().attr(ENDPOINT_URL_KEY).set(hello.getEndpointUrl()); long remoteProtocolVersion = hello.getProtocolVersion(); long remoteReceiveBufferSize = hello.getReceiveBufferSize(); long remoteSendBufferSize = hello.getSendBufferSize(); long remoteMaxMessageSize = hello.getMaxMessageSize(); long remoteMaxChunkCount = hello.getMaxChunkCount(); if (remoteProtocolVersion < PROTOCOL_VERSION) { throw new UaException(StatusCodes.Bad_ProtocolVersionUnsupported, "unsupported protocol version: " + remoteProtocolVersion); } ChannelConfig config = server.getChannelConfig(); /* Our receive buffer size is determined by the remote send buffer size. */ long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize()); /* Our send buffer size is determined by the remote receive buffer size. */ long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize()); /* Max chunk count the remote can send us; not influenced by remote configuration. */ long localMaxChunkCount = config.getMaxChunkCount(); /* Max message size the remote can send us. Determined by our max chunk count and receive buffer size. */ long localMaxMessageSize = Math.min(localReceiveBufferSize * localMaxChunkCount, config.getMaxMessageSize()); ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize), Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize), Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize), Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize), Ints.saturatedCast(remoteMaxChunkCount)); int maxArrayLength = config.getMaxArrayLength(); int maxStringLength = config.getMaxStringLength(); SerializationQueue serializationQueue = new SerializationQueue(server.getConfig().getExecutor(), parameters, maxArrayLength, maxStringLength); ctx.pipeline().addLast(new UaTcpServerAsymmetricHandler(server, serializationQueue)); ctx.pipeline().remove(this); logger.debug("[remote={}] Removed HelloHandler, added AsymmetricHandler.", ctx.channel().remoteAddress()); AcknowledgeMessage acknowledge = new AcknowledgeMessage(PROTOCOL_VERSION, localReceiveBufferSize, localSendBufferSize, localMaxMessageSize, localMaxChunkCount); ByteBuf messageBuffer = TcpMessageEncoder.encode(acknowledge); ctx.executor().execute(() -> ctx.writeAndFlush(messageBuffer)); logger.debug("[remote={}] Sent Acknowledge message.", ctx.channel().remoteAddress()); }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerSymmetricHandler.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, ServiceResponse message, ByteBuf out) throws Exception { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.buffer(); try {//from w w w. j a va2 s .co m binaryEncoder.setBuffer(messageBuffer); binaryEncoder.encodeMessage(null, message.getResponse()); final List<ByteBuf> chunks = chunkEncoder.encodeSymmetric(secureChannel, MessageType.SecureMessage, messageBuffer, message.getRequestId()); ctx.executor().execute(() -> { chunks.forEach(c -> ctx.write(c, ctx.voidPromise())); ctx.flush(); }); } catch (UaException e) { logger.error("Error encoding {}: {}", message.getResponse().getClass(), e.getMessage(), e); ctx.close(); } finally { messageBuffer.release(); } }); }
From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override/*ww w . ja v a2 s . co m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, request.dstAddrType(), request.dstAddr(), request.dstPort())); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:com.flysoloing.learning.network.netty.http2.tiles.Http1RequestHandler.java
License:Apache License
@Override protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency, final FullHttpResponse response, final FullHttpRequest request) { HttpUtil.setContentLength(response, response.content().readableBytes()); ctx.executor().schedule(new Runnable() { public void run() { if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.writeAndFlush(response); } else { ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }/*from w w w. j av a2s. co m*/ } }, latency, TimeUnit.MILLISECONDS); }
From source file:com.flysoloing.learning.network.netty.http2.tiles.Http2RequestHandler.java
License:Apache License
protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency, final FullHttpResponse response, final FullHttpRequest request) { setContentLength(response, response.content().readableBytes()); streamId(response, streamId);//from ww w .jav a 2 s . c o m ctx.executor().schedule(new Runnable() { public void run() { ctx.writeAndFlush(response); } }, latency, TimeUnit.MILLISECONDS); }
From source file:com.flysoloing.learning.network.netty.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); }/*from w ww. j a va 2s . co m*/ }); } else { ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, request.dstAddrType(), request.dstAddr(), request.dstPort())); responseFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:com.frank.netty.protocol.netty.client.HeartBeatReqHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage) msg; // ?????// ww w .j a v a 2 s. co m if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) { heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS); } else if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) { System.out.println("Client receive server heart beat message : ---> " + message); } else ctx.fireChannelRead(msg); }
From source file:com.fsocks.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); }//from w ww. j a v a 2 s . c om }); } else { ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { //??successclient ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, request.dstAddrType(), request.dstAddr(), request.dstPort())); responseFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) { //clientremote???????local proxy ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); //? logger.info("? addressType : " + request.dstAddrType() + ", cmdType:" + request.type() + ", host:" + request.dstAddr() + ", port:" + request.dstPort()); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results logger.info("?? addressType : " + request.dstAddrType() + ", cmdType:" + request.type() + ", host:" + request.dstAddr() + ", port:" + request.dstPort()); } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }