List of usage examples for io.netty.channel ChannelFutureListener CLOSE
ChannelFutureListener CLOSE
To view the source code for io.netty.channel ChannelFutureListener CLOSE.
Click Source Link
From source file:me.zhuoran.amoeba.netty.server.HttpServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) { if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);//from w w w. j a v a 2s .com buf.release(); HttpHeaders.setContentLength(res, (long) res.content().readableBytes()); } ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:monica.files.socket.FileServerHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace();/*www . j a v a 2s.c o m*/ if (ctx.channel().isActive()) { ctx.writeAndFlush("ERR: " + cause.getClass().getSimpleName() + ": " + cause.getMessage() + '\n') .addListener(ChannelFutureListener.CLOSE); } }
From source file:name.osipov.alexey.server.ServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); return; }//from ww w . jav a 2s. c o m //String passkey = req.headers().get("passkey"); // in case of large output this buffer will demand memory // writing directly to channel maybe more efficient... ByteBufOutputStream bufstream = new ByteBufOutputStream(Unpooled.buffer()); JsonGenerator json = new JsonFactory().createGenerator(bufstream); json.writeStartObject(); HttpResponseStatus status = HttpResponseStatus.INTERNAL_SERVER_ERROR; switch (req.getUri()) { case "/register": { User u = users.Register(); json.writeNumberField("id", u.getId()); json.writeBinaryField("key", u.getKey().asBinary()); status = HttpResponseStatus.OK; } break; case "/statistics": { String hashed_key_base64 = req.headers().get("key"); byte[] hashed_key = Base64.decodeBase64(hashed_key_base64); long salt = System.currentTimeMillis() / 1000 / 30; User u = users.getBySaltedHash(hashed_key, salt); if (u != null) { u.requestHappen(); json.writeNumberField("id", u.getId()); json.writeNumberField("requests", u.getRequests()); status = HttpResponseStatus.OK; } else status = HttpResponseStatus.UNAUTHORIZED; } break; } json.writeEndObject(); json.close(); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, bufstream.buffer()); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); if (!HttpHeaders.isKeepAlive(req)) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:net.anyflow.lannister.client.MqttClient.java
License:Apache License
public void disconnect(boolean sendDisconnect) { if (!isConnected()) { return;//ww w . j a va2 s . co m } if (sendDisconnect) { send(MessageFactory.disconnect()); } channel.disconnect().addListener(ChannelFutureListener.CLOSE); group.shutdownGracefully(); channel = null; group = null; }
From source file:net.anyflow.lannister.packetreceiver.ConnectReceiver.java
License:Apache License
private void sendNoneAcceptMessage(ChannelHandlerContext ctx, MqttConnectReturnCode returnCode) { assert returnCode != MqttConnectReturnCode.CONNECTION_ACCEPTED; MqttConnAckMessage msg = MessageFactory.connack(returnCode, false); // [MQTT-3.2.2-4] ctx.channel().writeAndFlush(msg).addListener(f -> { Plugins.SELF.get(ConnectEventListener.class).connectHandled(new ConnectEventArgs() { @Override/*from w w w .jav a2 s .com*/ public String clientId() { return null; } @Override public IMessage will() { return null; } @Override public Boolean cleanSession() { return null; } @Override public MqttConnectReturnCode returnCode() { return returnCode; } }); ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> // [MQTT-3.2.2-5],[MQTT-3.1.4-5] Plugins.SELF.get(DisconnectEventListener.class).disconnected(new AbnormalDisconnectEventArgs())); }); }
From source file:net.anyflow.lannister.packetreceiver.GenericReceiver.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) throws Exception { if (msg.decoderResult().isSuccess() == false) { logger.error("decoding MQTT message failed : {}", msg.decoderResult().cause().getMessage()); Session session = Session.NEXUS.get(ctx.channel().id()); if (session != null) { session.dispose(true); // [MQTT-4.8.0-1] } else {//from ww w .j a va 2 s. c o m ctx.channel().writeAndFlush(msg).addListener(f -> { logger.debug("packet outgoing [{}]", msg); ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> // [MQTT-3.2.2-5] Plugins.SELF.get(DisconnectEventListener.class) .disconnected(new AbnormalDisconnectEventArgs())); }); } return; } else { logger.debug("packet incoming [message={}]", msg.toString()); Session session = Session.NEXUS.get(ctx.channel().id()); if (session == null) { logger.error("None exist session message : {}", msg.toString()); ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> // [MQTT-4.8.0-1] Plugins.SELF.get(DisconnectEventListener.class).disconnected(new AbnormalDisconnectEventArgs())); return; } session.setLastIncomingTime(new Date()); switch (msg.fixedHeader().messageType()) { case DISCONNECT: DisconnectReceiver.SHARED.handle(session); return; case PINGREQ: PingReqReceiver.SHARED.handle(session); return; case PUBREC: PubRecReceiver.SHARED.handle(session, ((MqttMessageIdVariableHeader) msg.variableHeader()).messageId()); return; case PUBREL: PubRelReceiver.SHARED.handle(session, ((MqttMessageIdVariableHeader) msg.variableHeader()).messageId()); return; case PUBCOMP: PubCompReceiver.SHARED.handle(session, ((MqttMessageIdVariableHeader) msg.variableHeader()).messageId()); return; default: session.dispose(true); // [MQTT-4.8.0-1] return; } } }
From source file:net.anyflow.lannister.packetreceiver.GenericReceiver.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error(cause.getMessage(), cause); Session session = Session.NEXUS.get(ctx.channel().id()); if (session != null) { session.dispose(true);/* w w w . ja va2 s . c o m*/ } else { ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> // [MQTT-3.2.2-5] Plugins.SELF.get(DisconnectEventListener.class).disconnected(new AbnormalDisconnectEventArgs())); } }
From source file:net.anyflow.lannister.packetreceiver.PubAckReceiver.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, MqttPubAckMessage msg) throws Exception { logger.debug("packet incoming [message={}]", msg.toString()); Session session = Session.NEXUS.get(ctx.channel().id()); if (session == null) { logger.error("None exist session message [message={}]", msg.toString()); ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> // [MQTT-4.8.0-1] Plugins.SELF.get(DisconnectEventListener.class).disconnected(new AbnormalDisconnectEventArgs())); return;//ww w . ja v a 2 s.c o m } session.setLastIncomingTime(new Date()); String clientId = session.clientId(); int messageId = msg.variableHeader().messageId(); Topic topic = Topic.NEXUS.get(clientId, messageId, ClientType.SUBSCRIBER); if (topic == null) { logger.error("Topic does not exist [clientId={}, messageId={}]", clientId, messageId); session.dispose(true); // [MQTT-3.3.5-2] return; } final TopicSubscriber topicSubscriber = topic.subscribers().get(clientId); OutboundMessageStatus status = topicSubscriber.outboundMessageStatuses().get(messageId); if (status != null) { Plugins.SELF.get(DeliveredEventListener.class).delivered(new DeliveredEventArgs() { @Override public String clientId() { return clientId; } @Override public int messageId() { return messageId; } }); } topicSubscriber.removeOutboundMessageStatus(messageId); logger.debug("Outbound message status REMOVED [clientId={}, messageId={}]", clientId, messageId); }
From source file:net.anyflow.lannister.packetreceiver.PublishReceiver.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, MqttPublishMessage msg) throws Exception { logger.debug("packet incoming [message={}]", msg.toString()); Statistics.SELF.add(Statistics.Criterion.MESSAGES_PUBLISH_RECEIVED, 1); Session session = Session.NEXUS.get(ctx.channel().id()); if (session == null) { logger.error("None exist session message [message={}]", msg.toString()); ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> // [MQTT-4.8.0-1] Plugins.SELF.get(DisconnectEventListener.class).disconnected(new AbnormalDisconnectEventArgs())); return;//from w w w . j a v a 2 s . c o m } session.setLastIncomingTime(new Date()); if (!TopicMatcher.isValid(msg.variableHeader().topicName(), false)) { session.dispose(true); return; } Message message = Message.newMessage(session.clientId(), msg); if (!Plugins.SELF.get(PublishEventListener.class).allowPublish(new PublishEventArgs() { @Override public IMessage message() { return message; } })) { session.dispose(true); return; } // TODO What to do when sender re-publish message corrensponds to // unacked status? // TODO Until it has received the corresponding PUBREL packet, the // Receiver MUST acknowledge any subsequent PUBLISH packet with the same // Packet Identifier by sending a PUBREC. It MUST NOT cause duplicate // messages to be delivered to any onward recipients in this // case.[MQTT-4.3.3-2]. final Topic topic = Topic.NEXUS.publish(message); switch (msg.fixedHeader().qosLevel()) { case AT_MOST_ONCE: return; // QoS 0 do not send any acknowledge packet [MQTT-3.3.4-1] case AT_LEAST_ONCE: session.send(MessageFactory.puback(msg.variableHeader().messageId())).addListener( f -> topic.removeInboundMessageStatus(session.clientId(), msg.variableHeader().messageId())); // [MQTT-3.3.4-1],[MQTT-2.3.1-6] logger.debug("Inbound message status REMOVED [clientId={}, messageId={}]", session.clientId(), msg.variableHeader().messageId()); return; case EXACTLY_ONCE: session.send(MessageFactory.pubrec(msg.variableHeader().messageId())) .addListener(f -> topic.setInboundMessageStatus(session.clientId(), msg.variableHeader().messageId(), InboundMessageStatus.Status.PUBRECED)); // [MQTT-3.3.4-1],[MQTT-2.3.1-6] return; default: session.dispose(true); // [MQTT-3.3.1-4] return; } }
From source file:net.anyflow.lannister.packetreceiver.SubscribeReceiver.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, MqttSubscribeMessage msg) throws Exception { logger.debug("packet incoming [message={}]", msg.toString()); Session session = Session.NEXUS.get(ctx.channel().id()); if (session == null) { logger.error("None exist session message [message={}]", msg.toString()); ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> // [MQTT-4.8.0-1] Plugins.SELF.get(DisconnectEventListener.class).disconnected(new AbnormalDisconnectEventArgs())); return;//w w w .ja v a 2 s .co m } session.setLastIncomingTime(new Date()); List<MqttTopicSubscription> topicSubs = msg.payload().topicSubscriptions(); if (topicSubs == null || topicSubs.isEmpty()) { session.dispose(true); // [MQTT-4.8.0-1] return; } // TODO multiple sub checking (granted QoS) Map.Entry<List<Integer>, Map<String, TopicSubscription>> returns = generateReturns(topicSubs); List<Integer> grantedQoss = returns.getKey(); Map<String, TopicSubscription> topicSubscriptions = returns.getValue(); if (!executePlugins(session, topicSubscriptions.values())) { return; } session.topicSubscriptions().putAll(topicSubscriptions); session.send(MessageFactory.suback(msg.variableHeader().messageId(), grantedQoss)); // [MQTT-2.3.1-7],[MQTT-2.3.1-7],[MQTT-3.8.4-1],[MQTT-3.8.4-2] sendRetainedMessage(session, topicSubscriptions); publishStatic$Sys(session, topicSubscriptions.values()); // TODO [MQTT-3.3.1-7] }