List of usage examples for io.netty.channel ChannelHandlerContext channel
Channel channel();
From source file:chapter10.WebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // //from w ww . j av a2 s . c o m if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); setContentLength(res, res.content().readableBytes()); } // ?Keep-Alive ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:ChatServer.ChatServerHandler.java
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { Channel incomming = ctx.channel(); for (Channel channel : channels) { channel.writeAndFlush(new NewUser(1, incomming.remoteAddress().toString(), null, null)); }/*w ww . j ava 2s.c o m*/ channels.add(ctx.channel()); }
From source file:ChatServer.ChatServerHandler.java
@Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { Channel incomming = ctx.channel(); for (Channel channel : channels) { channel.writeAndFlush(new Logout(1)); }//ww w. j av a 2s . c o m channels.remove(ctx.channel()); }
From source file:ChatServer.ChatServerHandler.java
@Override protected void channelRead0(ChannelHandlerContext chc, Messages.Message i) throws Exception { Channel incomming = chc.channel(); for (Channel channel : channels) { if (channel != incomming) { channel.writeAndFlush(i);/*from w w w.j a v a 2 s . c o m*/ } } }
From source file:cloudeventbus.server.ServerHandler.java
License:Open Source License
@Override public void messageReceived(ChannelHandlerContext context, Frame frame) throws Exception { resetIdleTask(context.channel().eventLoop()); LOGGER.debug("Received frame on server: {}", frame); switch (frame.getFrameType()) { case AUTH_RESPONSE: { AuthenticationResponseFrame authenticationResponse = (AuthenticationResponseFrame) frame; final CertificateChain certificates = authenticationResponse.getCertificates(); serverConfig.getTrustStore().validateCertificateChain(certificates); this.clientCertificates = certificates; CertificateUtils.validateSignature(certificates.getLast().getPublicKey(), challenge, authenticationResponse.getSalt(), authenticationResponse.getDigitalSignature()); switch (certificates.getLast().getType()) { case AUTHORITY: throw new InvalidCertificateException( "Can not use an authority certificate to authenticate to server."); case CLIENT: serverConnection = false;// w ww . j av a 2 s. c om break; case SERVER: serverConnection = true; clusterManager.addPeer(new ServerPeer(clientId, context.channel())); break; } serverReady = true; context.write(ServerReadyFrame.SERVER_READY); break; } case AUTHENTICATE: { if (!serverConfig.hasSecurityCredentials()) { throw new CloudEventBusServerException( "Unable to authenticate with server, missing private key or certificate chain"); } final AuthenticationRequestFrame authenticationRequest = (AuthenticationRequestFrame) frame; final byte[] salt = CertificateUtils.generateChallenge(); final byte[] signature = CertificateUtils.signChallenge(serverConfig.getPrivateKey(), authenticationRequest.getChallenge(), salt); AuthenticationResponseFrame authenticationResponse = new AuthenticationResponseFrame( serverConfig.getCertificateChain(), salt, signature); context.write(authenticationResponse); break; } case GREETING: final GreetingFrame greetingFrame = (GreetingFrame) frame; clientAgent = greetingFrame.getAgent(); clientId = greetingFrame.getId(); if (greetingFrame.getVersion() != Constants.PROTOCOL_VERSION) { throw new InvalidProtocolVersionException( "This server doesn't support protocol version " + greetingFrame.getVersion()); } // TODO Try moving this back to channelActive and see if server still crashes... context.write(new GreetingFrame(Constants.PROTOCOL_VERSION, serverConfig.getAgentString(), serverConfig.getId())); if (serverConfig.getTrustStore() == null) { serverReady = true; context.write(ServerReadyFrame.SERVER_READY); } else { challenge = CertificateUtils.generateChallenge(); context.write(new AuthenticationRequestFrame(challenge)); } break; case PONG: // Do nothing. break; default: if (!serverReady) { throw new ServerNotReadyException("This server requires authentication."); } else { switch (frame.getFrameType()) { case PUBLISH: { final PublishFrame publishFrame = (PublishFrame) frame; final Subject subject = publishFrame.getSubject(); final String body = publishFrame.getBody(); if (clientCertificates != null) { clientCertificates.getLast().validatePublishPermission(subject); } final Subject replySubject = publishFrame.getReplySubject(); // Implicitly subscribe to request reply subjects if (replySubject != null && replySubject.isRequestReply()) { clientSubscriptionHub.subscribe(replySubject, handler); } // If the publish is coming from a peer server, publish locally if (serverConnection) { hub.publish(subject, replySubject, body); } else { hub.broadcast(subject, replySubject, body); } break; } case SUBSCRIBE: { final SubscribeFrame subscribeFrame = (SubscribeFrame) frame; final Subject subject = subscribeFrame.getSubject(); if (clientCertificates != null) { clientCertificates.getLast().validateSubscribePermission(subject); } if (subscriptionHandles.containsKey(subject)) { throw new DuplicateSubscriptionException("Already subscribed to subject " + subject); } // If the connection is a peer server, let the ClusterManager forward messages instead of the normal subscription mechanism if (!serverConnection) { final SubscriptionHandle subscriptionHandle = clientSubscriptionHub.subscribe(subject, handler); subscriptionHandles.put(subject, subscriptionHandle); } break; } case UNSUBSCRIBE: { final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame; final Subject subject = unsubscribeFrame.getSubject(); final SubscriptionHandle subscriptionHandle = subscriptionHandles.get(subject); if (subscriptionHandle == null) { throw new NotSubscribedException("Not subscribed to subject " + subject); } subscriptionHandle.remove(); break; } case PING: context.write(PongFrame.PONG); break; default: throw new CloudEventBusServerException( "Unable to handle frame of type " + frame.getClass().getName()); } } } }
From source file:cloudeventbus.server.ServerHandler.java
License:Open Source License
@Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { LOGGER.debug("Channel active from {}", ctx.channel().remoteAddress()); idleTask = new Runnable() { @Override//from w ww. j a v a 2 s . c o m public void run() { LOGGER.warn("Idle connection {}", ctx.channel().remoteAddress()); error(ctx, new ErrorFrame(ErrorFrame.Code.IDLE_TIMEOUT, "Connection closed for idle timeout")); } }; pingTask = new Runnable() { @Override public void run() { ctx.write(PingFrame.PING); } }; resetIdleTask(ctx.channel().eventLoop()); handler = new NettyHandler(ctx); }
From source file:cloudeventbus.server.ServerHandler.java
License:Open Source License
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOGGER.debug("Channel inactive from {}", ctx.channel().remoteAddress()); // Cleanup subscriptions in hub for (SubscriptionHandle handle : subscriptionHandles.values()) { handle.remove();//from w ww .ja v a 2s. c om } // Cancel idle check and ping tasks. if (idleFuture != null) { idleFuture.cancel(false); } if (pingFuture != null) { pingFuture.cancel(false); } }
From source file:cloudfoundry.norouter.f5.dropsonde.LineEventToMetronServer.java
License:Open Source License
@Autowired public LineEventToMetronServer(@Qualifier("boss") EventLoopGroup boss, @Qualifier("worker") EventLoopGroup worker, RouteRegistrar routeRegistrar, MetronClient metronClient, F5Properties properties) { final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w w w . ja va2 s . c om*/ protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new LineBasedFrameDecoder(64 * 1024)); ch.pipeline().addLast(new LineEventDecoder()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOGGER.warn("An error occurred processing logging events from the LTM.", cause); ctx.close(); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { LOGGER.info("New connection from {}", ctx.channel().remoteAddress()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof LogEvent) { final LogEvent logEvent = (LogEvent) msg; final RouteDetails routeDetails = routeRegistrar .getRouteByAddress(logEvent.getApplicationAddress()); if (routeDetails != null && routeDetails.getApplicationGuid() != null) { final String appGuid = routeDetails.getApplicationGuid().toString(); final String message = logEvent.getMessage() + " app_id:" + appGuid; metronClient.createLogEmitter("RTR", logEvent.getLtmIdentifier()) .emit(logEvent.getTimestamp(), appGuid, message); } } else { super.channelRead(ctx, msg); } } }); } }); bootstrap.bind(properties.getLoggingPort()).syncUninterruptibly(); LOGGER.info("Listening for logging events from the LTM on port {}", properties.getLoggingPort()); }
From source file:club.jmint.crossing.server.ServerHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); CrossLog.logger.info("Client accepted: " + ctx.channel().remoteAddress().toString()); }
From source file:club.jmint.crossing.server.ServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { CrossingReqProto.CrossingReq req = (CrossingReqProto.CrossingReq) msg; CrossingRespProto.CrossingResp resp; CrossLog.logger.debug("Received Request:\n" + req.toString()); try {/*from w w w . j a v a 2 s. c o m*/ long time_start = Utils.getTimeInMillis(); ReqMsg rm = new ReqMsg(); rm.seqId = req.getSeqId(); rm.inf = req.getInterfaceName(); rm.params = req.getParams(); rm.isEncrypt = req.getIsEncrypt(); //Check interface access rights InetSocketAddress isa = (InetSocketAddress) ctx.channel().remoteAddress(); String clientIp = Utils.getReadableIPString(isa.getAddress().getAddress()); if (!aw.isIpAccessible(clientIp)) { CrossLog.logger.error("IP unauthorized: " + clientIp); resp = createResp(req, ParamBuilder.createErrorParams(ErrorCode.CROSSING_ERR_UNAUTHORIZED_IP.getCode(), ErrorCode.CROSSING_ERR_UNAUTHORIZED_IP.getInfo())); ctx.writeAndFlush(resp); return; } if (!aw.isInterfaceAccessible(clientIp, rm.inf)) { CrossLog.logger.error("Call unauthorized: " + clientIp + " --> " + rm.inf); resp = createResp(req, ParamBuilder.createErrorParams(ErrorCode.CROSSING_ERR_UNAUTHORIZED_INF.getCode(), ErrorCode.CROSSING_ERR_UNAUTHORIZED_INF.getInfo())); ctx.writeAndFlush(resp); return; } //MyLog.logger.info("Call authorized: " + clientIp + " --> " + inf); rm.ip = clientIp; //do Service Call String resParams = shandler.handle(rm); resp = createResp(req, resParams); ctx.writeAndFlush(resp); CrossLog.logger.debug("Send response:\n" + resp.toString()); //Client side Statistics long time_end = Utils.getTimeInMillis(); long delay = time_end - time_start; ClientCallStats ccs = StatsWizard.getClientCallStats(clientIp); ccs.setTimes(ccs.getTimes() + 1); ccs.setMaxDelays(delay); ccs.setMinDelays(delay); ccs.addToTotalDelay(delay); ccs.incCounterPair(rm.inf); if (ParamBuilder.getErrorCode(resParams) == 0) { ccs.setSuccesses(ccs.getSuccesses() + 1); CrossLog.logger.info("Call succeeded: " + clientIp + " --> " + rm.inf + "(" + resParams + ")"); } else { ccs.setFailures(ccs.getFailures() + 1); CrossLog.logger.info("Call failed: " + clientIp + " --> " + rm.inf + "(" + resParams + ")"); } } catch (CrossException ce) { CrossLog.logger.error("Server handle error."); CrossLog.printStackTrace(ce); resp = createResp(req, ParamBuilder.createErrorParams(ce.getErrorCode(), ce.getErrorInfo())); ctx.writeAndFlush(resp); return; } catch (Exception e) { // CrossLog.logger.error("Server handle error."); CrossLog.printStackTrace(e); resp = createResp(req, ParamBuilder.createErrorParams(ErrorCode.CROSSING_ERR_INTERNAL.getCode(), ErrorCode.CROSSING_ERR_INTERNAL.getInfo())); ctx.writeAndFlush(resp); return; } }