io.netty.channel.ChannelFutureListener Java Examples
The following examples show how to use
io.netty.channel.ChannelFutureListener.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TelnetServerHandler2.java From netty.book.kor with MIT License | 6 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { String response; boolean close = false; if (request.isEmpty()) { response = "명령을 입력해 주세요2.\r\n"; } else if ("bye".equals(request.toLowerCase())) { response = "좋은 하루 되세요2!\r\n"; close = true; } else { response = "입력하신 명령이 '" + request + "' 입니까2?\r\n"; } ChannelFuture future = ctx.write(response); if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
Example #2
Source File: AbstractBootstrap.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
private static void doBind0( final ChannelFuture regFuture, final Channel channel, final SocketAddress localAddress, final ChannelPromise promise) { // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up // the pipeline in its channelRegistered() implementation. channel.eventLoop().execute(new Runnable() { @Override public void run() { if (regFuture.isSuccess()) { channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } else { promise.setFailure(regFuture.cause()); } } }); }
Example #3
Source File: WebsocketServerOperations.java From reactor-netty with Apache License 2.0 | 6 votes |
Mono<Void> sendClose(CloseWebSocketFrame frame) { if (CLOSE_SENT.get(this) == 0) { //commented for now as we assume the close is always scheduled (deferFuture runs) //onTerminate().subscribe(null, null, () -> ReactorNetty.safeRelease(frame)); return FutureMono.deferFuture(() -> { if (CLOSE_SENT.getAndSet(this, 1) == 0) { discard(); onCloseState.onNext(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText())); return channel().writeAndFlush(frame) .addListener(ChannelFutureListener.CLOSE); } frame.release(); return channel().newSucceededFuture(); }).doOnCancel(() -> ReactorNetty.safeRelease(frame)); } frame.release(); return Mono.empty(); }
Example #4
Source File: WebsocketClientOperations.java From reactor-netty with Apache License 2.0 | 6 votes |
Mono<Void> sendClose(CloseWebSocketFrame frame) { if (CLOSE_SENT.get(this) == 0) { //commented for now as we assume the close is always scheduled (deferFuture runs) //onTerminate().subscribe(null, null, () -> ReactorNetty.safeRelease(frame)); return FutureMono.deferFuture(() -> { if (CLOSE_SENT.getAndSet(this, 1) == 0) { discard(); onCloseState.onNext(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText())); return channel().writeAndFlush(frame) .addListener(ChannelFutureListener.CLOSE); } frame.release(); return channel().newSucceededFuture(); }).doOnCancel(() -> ReactorNetty.safeRelease(frame)); } frame.release(); return Mono.empty(); }
Example #5
Source File: PacketEncryption.java From The-5zig-Mod with GNU General Public License v3.0 | 6 votes |
@Override public void handle() { final SecretKey secretKey = CryptManager.createNewSharedKey(); String hash = (new BigInteger(CryptManager.getServerIdHash("", publicKey, secretKey))).toString(16); MinecraftSessionService yggdrasil = new YggdrasilAuthenticationService(The5zigMod.getVars().getProxy(), UUID.randomUUID().toString()).createMinecraftSessionService(); try { yggdrasil.joinServer(The5zigMod.getVars().getGameProfile(), The5zigMod.getDataManager().getSession(), hash); } catch (AuthenticationException e) { The5zigMod.getNetworkManager().disconnect(I18n.translate("connection.bad_login")); throw new RuntimeException(e); } The5zigMod.getNetworkManager().sendPacket(new PacketEncryption(secretKey, publicKey, verifyToken), new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { The5zigMod.getNetworkManager().enableEncryption(secretKey); } }); }
Example #6
Source File: HttpHelloWorldServerHandler.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } }
Example #7
Source File: Http1RequestHandler.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@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() { @Override public void run() { if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.writeAndFlush(response); } else { ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } }, latency, TimeUnit.MILLISECONDS); }
Example #8
Source File: NettySimpleAmqpServer.java From qpid-jms with Apache License 2.0 | 6 votes |
void pumpProtonToChannel(ChannelHandlerContext ctx, ChannelFutureListener writeCompletionAction) { boolean done = false; while (!done) { ByteBuffer toWrite = protonTransport.getOutputBuffer(); if (toWrite != null && toWrite.hasRemaining()) { LOG.trace("Server: Sending {} bytes out", toWrite.limit()); ctx.write(Unpooled.wrappedBuffer(toWrite)); toWrite.position(toWrite.limit()); protonTransport.outputConsumed(); } else { done = true; } } if (writeCompletionAction != null) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(writeCompletionAction); } else { ctx.flush(); } }
Example #9
Source File: ProxyChannelDao.java From proxy with MIT License | 6 votes |
public void bindForTCP(Integer serverPort, ServerBootstrap bootstrap, ProxyRealServer proxyRealServer) { bootstrap.bind(serverPort).addListener((ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { logger.info("绑定本地服务端口({})成功 客户端({})--{}", serverPort, proxyRealServer.getClientKey(), proxyRealServer.getDescription()); //绑定成功 ProxyChannel proxyChannel = new ProxyChannel(); proxyChannel.setPort(serverPort); proxyChannel.setChannel(channelFuture.channel()); proxyChannel.setBootstrap(bootstrap); proxyChannel.setClientKey(proxyRealServer.getClientKey()); proxyChannel.setProxyType(CommonConstant.ProxyType.TCP); proxyChannelCache.put(serverPort, proxyChannel); //设置状态 proxyRealServer.setStatus(CommonConstant.ProxyStatus.ONLINE); } else { logger.error("绑定本地服务端口{}失败", serverPort); } }); }
Example #10
Source File: HttpCacheServerHandler.java From bazel with Apache License 2.0 | 6 votes |
private void handleGet(ChannelHandlerContext ctx, FullHttpRequest request) { if (!isUriValid(request.uri())) { sendError(ctx, request, HttpResponseStatus.BAD_REQUEST); return; } byte[] contents = cache.get(request.uri()); if (contents == null) { sendError(ctx, request, HttpResponseStatus.NOT_FOUND); return; } FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(contents)); HttpUtil.setContentLength(response, contents.length); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream"); ChannelFuture lastContentFuture = ctx.writeAndFlush(response); if (!HttpUtil.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
Example #11
Source File: HelloWorldHttp1Handler.java From netty-cookbook with Apache License 2.0 | 6 votes |
@Override public void messageReceived(ChannelHandlerContext ctx, HttpRequest req) throws Exception { if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); ByteBuf content = ctx.alloc().buffer(); content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate()); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.writeAndFlush(response); } }
Example #12
Source File: NettyClientTransport.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Override public void ping(final PingCallback callback, final Executor executor) { if (channel == null) { executor.execute(new Runnable() { @Override public void run() { callback.onFailure(statusExplainingWhyTheChannelIsNull.asException()); } }); return; } // The promise and listener always succeed in NettyClientHandler. So this listener handles the // error case, when the channel is closed and the NettyClientHandler no longer in the pipeline. ChannelFutureListener failureListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { Status s = statusFromFailedFuture(future); Http2Ping.notifyFailed(callback, executor, s.asException()); } } }; // Write the command requesting the ping handler.getWriteQueue().enqueue(new SendPingCommand(callback, executor), true) .addListener(failureListener); }
Example #13
Source File: ProxyToServerConnection.java From PowerTunnel with MIT License | 6 votes |
protected Future<?> execute() { LOG.debug("Handling CONNECT request through Chained Proxy"); chainedProxy.filterRequest(initialRequest); boolean isMitmEnabled = isMITMEnabled(); /* * We ignore the LastHttpContent which we read from the client * connection when we are negotiating connect (see readHttp() * in ProxyConnection). This cannot be ignored while we are * doing MITM + Chained Proxy because the HttpRequestEncoder * of the ProxyToServerConnection will be in an invalid state * when the next request is written. Writing the EmptyLastContent * resets its state. */ if(isMitmEnabled){ ChannelFuture future = writeToChannel(initialRequest); future.addListener((ChannelFutureListener) arg0 -> { if(arg0.isSuccess()){ writeToChannel(LastHttpContent.EMPTY_LAST_CONTENT); } }); return future; } else { return writeToChannel(initialRequest); } }
Example #14
Source File: Http2MultiplexCodecTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void channelClosedWhenCloseListenerCompletes() { LastInboundHandler inboundHandler = streamActiveAndWriteHeaders(inboundStream); Http2StreamChannel childChannel = (Http2StreamChannel) inboundHandler.channel(); assertTrue(childChannel.isOpen()); assertTrue(childChannel.isActive()); final AtomicBoolean channelOpen = new AtomicBoolean(true); final AtomicBoolean channelActive = new AtomicBoolean(true); // Create a promise before actually doing the close, because otherwise we would be adding a listener to a future // that is already completed because we are using EmbeddedChannel which executes code in the JUnit thread. ChannelPromise p = childChannel.newPromise(); p.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { channelOpen.set(future.channel().isOpen()); channelActive.set(future.channel().isActive()); } }); childChannel.close(p).syncUninterruptibly(); assertFalse(channelOpen.get()); assertFalse(childChannel.isActive()); }
Example #15
Source File: HttpHandler.java From smartacus-mqtt-broker with Apache License 2.0 | 6 votes |
private void getConnections(ChannelHandlerContext ctx, ConcurrentHashMap<String,ClientConnection> connectionFactory) { ArrayList<ClientConnectionVO> vos = new ArrayList<>(); if(null !=connectionFactory && !connectionFactory.isEmpty()){ connectionFactory.forEach((k,v)->{ ClientConnectionVO vo=new ClientConnectionVO(); vo.setClientId(v.getClientId()); vo.setUsername(v.getUsername()); vo.setIp(v.getIp()); vo.setPort(v.getPort()); vo.setConnectedDate(v.getConnectedDate()); vo.setProtocolVersion(v.getProtocolVersion()); vo.setPassword(v.getPassword()); vos.add(vo); }); } // 1.设置响应 Result result= new Result<Object>().ok(vos); FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(JSONObject.toJSONString(result), CharsetUtil.UTF_8)); resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); // 2.发送 // 注意必须在使用完之后,close channel ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE); }
Example #16
Source File: NettyConnectionManager.java From eagle with Apache License 2.0 | 6 votes |
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state().equals(IdleState.ALL_IDLE)) { final String remoteAddress = RemotingUtil.parseChannelRemoteAddr(ctx.channel()); logger.warn("NETTY CLIENT PIPELINE: IDLE exception [{}]", remoteAddress); HeartBeatFactory heartBeatFactory = SpiClassLoader.getClassLoader(HeartBeatFactory.class).getExtension(config.getExt(ConfigEnum.heartbeatFactory.getName(), ConfigEnum.heartbeatFactory.getValue())); ctx.writeAndFlush(heartBeatFactory.createRequest()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { client.resetErrorCount(); } } }); } } ctx.fireUserEventTriggered(evt); }
Example #17
Source File: Broker2Client.java From DDMQ with Apache License 2.0 | 6 votes |
public void checkProducerTransactionState( final Channel channel, final CheckTransactionStateRequestHeader requestHeader, final SelectMappedBufferResult selectMappedBufferResult) { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_TRANSACTION_STATE, requestHeader); request.markOnewayRPC(); try { FileRegion fileRegion = new OneMessageTransfer(request.encodeHeader(selectMappedBufferResult.getSize()), selectMappedBufferResult); channel.writeAndFlush(fileRegion).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { selectMappedBufferResult.release(); if (!future.isSuccess()) { log.error("invokeProducer failed,", future.cause()); } } }); } catch (Throwable e) { log.error("invokeProducer exception", e); selectMappedBufferResult.release(); } }
Example #18
Source File: PacketEncryption.java From The-5zig-Mod with MIT License | 6 votes |
@Override public void handle() { final SecretKey secretKey = CryptManager.createNewSharedKey(); String hash = (new BigInteger(CryptManager.getServerIdHash("", publicKey, secretKey))).toString(16); MinecraftSessionService yggdrasil = new YggdrasilAuthenticationService(The5zigMod.getVars().getProxy(), UUID.randomUUID().toString()).createMinecraftSessionService(); try { yggdrasil.joinServer(The5zigMod.getVars().getGameProfile(), The5zigMod.getDataManager().getSession(), hash); } catch (AuthenticationException e) { The5zigMod.getNetworkManager().disconnect(I18n.translate("connection.bad_login")); throw new RuntimeException(e); } The5zigMod.getNetworkManager().sendPacket(new PacketEncryption(secretKey, publicKey, verifyToken), new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { The5zigMod.getNetworkManager().enableEncryption(secretKey); } }); }
Example #19
Source File: ReAuthContext.java From hivemq-community-edition with Apache License 2.0 | 6 votes |
@Override void succeedAuthentication(final @NotNull ReAuthOutput output) { super.succeedAuthentication(output); final Channel channel = ctx.channel(); channel.attr(ChannelAttributes.RE_AUTH_ONGOING).set(false); applyClientSettings(output.getClientSettings(), channel); final ChannelFuture authFuture = authSender.sendAuth( channel, output.getAuthenticationData(), Mqtt5AuthReasonCode.SUCCESS, Mqtt5UserProperties.of(output.getOutboundUserProperties().asInternalList()), output.getReasonString()); authFuture.addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { ctx.pipeline().fireUserEventTriggered(new OnAuthSuccessEvent()); } else if (future.channel().isActive()) { onSendException(future.cause()); } }); }
Example #20
Source File: Http2FrameCodecTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test(timeout = 5000) public void newOutboundStream() { final Http2FrameStream stream = frameCodec.newStream(); assertNotNull(stream); assertFalse(isStreamIdValid(stream.id())); final Promise<Void> listenerExecuted = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE); channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), false).stream(stream)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { assertTrue(future.isSuccess()); assertTrue(isStreamIdValid(stream.id())); listenerExecuted.setSuccess(null); } } ); ByteBuf data = Unpooled.buffer().writeZero(100); ChannelFuture f = channel.writeAndFlush(new DefaultHttp2DataFrame(data).stream(stream)); assertTrue(f.isSuccess()); listenerExecuted.syncUninterruptibly(); assertTrue(listenerExecuted.isSuccess()); }
Example #21
Source File: Ipcd10WebSocketServerHandler.java From arcusipcd with Apache License 2.0 | 6 votes |
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f; if (useSSL) { f = ctx.channel().writeAndFlush(res); } else { // TODO may not want to flush here -- only write f = ctx.channel().writeAndFlush(res); } if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
Example #22
Source File: AbstractGenericHandler.java From couchbase-jvm-core with Apache License 2.0 | 6 votes |
@Override public void onError(Throwable e) { if (ctx.channel() == null || !ctx.channel().isActive()) { return; } if (e instanceof TimeoutException) { endpoint.setLastKeepAliveLatency(TimeUnit.MILLISECONDS.toMicros(env().keepAliveTimeout())); } LOGGER.warn("{}Got error while consuming KeepAliveResponse.", logIdent(ctx, endpoint), e); keepAliveThreshold++; if (keepAliveThreshold >= env().keepAliveErrorThreshold()) { LOGGER.warn( "{}KeepAliveThreshold reached - " + "closing this socket proactively.", system(logIdent(ctx, endpoint))); ctx.close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { LOGGER.warn("Error while proactively closing the socket.", future.cause()); } } }); } }
Example #23
Source File: NettyMessagingService.java From atomix with Apache License 2.0 | 6 votes |
/** * Recursively binds the given bootstrap to the given interfaces. * * @param bootstrap the bootstrap to bind * @param ifaces an iterator of interfaces to which to bind * @param port the port to which to bind * @param future the future to completed once the bootstrap has been bound to all provided interfaces */ private void bind(ServerBootstrap bootstrap, Iterator<String> ifaces, int port, CompletableFuture<Void> future) { if (ifaces.hasNext()) { String iface = ifaces.next(); bootstrap.bind(iface, port).addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { log.info("TCP server listening for connections on {}:{}", iface, port); serverChannel = f.channel(); bind(bootstrap, ifaces, port, future); } else { log.warn("Failed to bind TCP server to port {}:{} due to {}", iface, port, f.cause()); future.completeExceptionally(f.cause()); } }); } else { future.complete(null); } }
Example #24
Source File: SelectorUtil.java From TakinRPC with Apache License 2.0 | 5 votes |
public static void closeChannel(Channel channel) { final String addrRemote = RemotingHelper.parseChannelRemoteAddr(channel); channel.close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { logger.info("closeChannel: close the connection to remote address[{}] result: {}", addrRemote, future.isSuccess()); } }); }
Example #25
Source File: MysqlProxyHandler.java From spring-boot-protocol with Apache License 2.0 | 5 votes |
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ServerErrorPacket errorPacket; if(cause instanceof ProxyException){ int errorNumber = ((ProxyException) cause).getErrorNumber(); errorPacket = new ServerErrorPacket( 0,errorNumber,"#HY000".getBytes(),cause.toString()); }else { errorPacket = new ServerErrorPacket( 0, ProxyException.ERROR_UNKOWN, "#HY000".getBytes(), cause.toString()); } ctx.channel().writeAndFlush(errorPacket) .addListener(ChannelFutureListener.CLOSE); }
Example #26
Source File: WebSocketServerProtocolHandler.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { if (frame instanceof CloseWebSocketFrame) { WebSocketServerHandshaker handshaker = getHandshaker(ctx); if (handshaker != null) { frame.retain(); handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); } else { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } return; } super.decode(ctx, frame, out); }
Example #27
Source File: Http2ConnectionRoundtripTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void listenerExceptionShouldCloseConnection() throws Exception { final Http2Headers headers = dummyHeaders(); doThrow(new RuntimeException("Fake Exception")).when(serverListener).onHeadersRead( any(ChannelHandlerContext.class), eq(3), eq(headers), eq(0), eq((short) 16), eq(false), eq(0), eq(false)); bootstrapEnv(1, 0, 1, 1); // Create a latch to track when the close occurs. final CountDownLatch closeLatch = new CountDownLatch(1); clientChannel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { closeLatch.countDown(); } }); // Create a single stream by sending a HEADERS frame to the server. runInChannel(clientChannel, new Http2Runnable() { @Override public void run() throws Http2Exception { http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, newPromise()); http2Client.flush(ctx()); } }); // Wait for the server to create the stream. assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); // Wait for the close to occur. assertTrue(closeLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS)); assertFalse(clientChannel.isOpen()); }
Example #28
Source File: HttpThriftBufDecoder.java From nettythrift with Apache License 2.0 | 5 votes |
private boolean directHandleMethod(ChannelHandlerContext ctx, FullHttpRequest request, HttpMethod method) { if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.POST)) { return false; } // 处理 OPTIONS 请求 HttpResponseStatus status = HttpResponseStatus.OK; boolean invalid = false; if (!method.equals(HttpMethod.OPTIONS)) { invalid = true; status = HttpResponseStatus.METHOD_NOT_ALLOWED; } DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.EMPTY_BUFFER); HttpHeaders headers = response.headers(); // headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, // "X-Requested-With, accept, origin, content-type"); headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "X-Requested-With, content-type"); headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS"); headers.set(HttpHeaderNames.SERVER, "Netty5"); if (invalid) { headers.set("Client-Warning", "Invalid Method"); } boolean keepAlive = HttpHeaderUtil.isKeepAlive(request); if (keepAlive) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(response); ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } return true; }
Example #29
Source File: PushMessageSender.java From zuul with Apache License 2.0 | 5 votes |
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus status, PushUserAuth userAuth) { final FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, status); resp.headers().add("Content-Length", "0"); final ChannelFuture cf = ctx.channel().writeAndFlush(resp); if (!HttpUtil.isKeepAlive(request)) { cf.addListener(ChannelFutureListener.CLOSE); } logPushEvent(request, status, userAuth); }
Example #30
Source File: MqttServer.java From smartacus-mqtt-broker with Apache License 2.0 | 5 votes |
public void run() throws Exception{ EventLoopGroup bossGroup=new NioEventLoopGroup(1); NioEventLoopGroup workerGroup=new NioEventLoopGroup(128); try{ //实例化session工厂和connection工厂 SessionManager sessionManager=new SessionManager(); ConnectionFactory connectionFactory=new ConnectionFactory(); ServerBootstrap sboot=new ServerBootstrap(); sboot.group(bossGroup,workerGroup) //设置通道类型 .channel(NioServerSocketChannel.class) //向通道的中添加handler初始化器 .childHandler(new MqttChannelChannelInitializer(sessionManager,connectionFactory)) .option(ChannelOption.SO_BACKLOG,1024) //设置子Socket的keepalive时间 .childOption(ChannelOption.SO_KEEPALIVE,true); //绑定端口号 Integer port=Integer.valueOf(SystemConfiguration.INSTANCE.getPort()); ChannelFuture cf = sboot.bind(port).sync(); System.out.println("Broker initiated..."); sboot.bind(port).addListeners(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { System.out.println("=========绑定完成=============="); // } }); cf.channel().closeFuture().sync(); }finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }