Example usage for io.netty.channel ChannelHandlerContext channel

List of usage examples for io.netty.channel ChannelHandlerContext channel

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext channel.

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:app.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        channels.remove(ctx.channel());
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/*from   w ww  . java2 s.  com*/
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (frame instanceof TextWebSocketFrame) {
        JSONObject msg = (JSONObject) JSONValue.parse(((TextWebSocketFrame) frame).text());

        if (msg == null) {
            System.out.println("Unknown message type");
            return;
        }

        switch (msg.get("type").toString()) {
        case "broadcast":
            final TextWebSocketFrame outbound = new TextWebSocketFrame(msg.toJSONString());
            channels.forEach(gc -> gc.writeAndFlush(outbound.duplicate().retain()));
            msg.replace("type", "broadcastResult");
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        case "echo":
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        default:
            System.out.println("Unknown message type");
        }

        return;
    }
}

From source file:app.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);//from  ww w . j ava 2  s . co m
        buf.release();
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:at.yawk.accordion.netty.NettyConnector.java

License:Mozilla Public License

@Override
public Optional<Connection> connect(SocketAddress address) {
    // TODO find a non-hacky method to close channels
    Collection<Channel> registeredChannels = Collections.synchronizedList(new ArrayList<>());

    EventLoopGroup workerGroup = new NioEventLoopGroup() {
        @Override//w w  w  . j  av a  2 s.co  m
        public ChannelFuture register(Channel channel, ChannelPromise promise) {
            registeredChannels.add(channel);
            return super.register(channel, promise);
        }
    };

    AtomicReference<Connection> connectionRef = new AtomicReference<>();

    // init
    Bootstrap bootstrap = new Bootstrap().group(workerGroup).handler(new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            NettyConnection connection = new NettyConnection(ctx.channel());
            connectionRef.set(connection);
            connection.init();
        }
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);

    try {
        // connect
        ChannelFuture connectFuture = bootstrap.connect(address);
        // wait for connection
        connectFuture.sync();
        return Optional.of(connectionRef.get());
    } catch (Exception e) {
        // shut down workers
        workerGroup.shutdownGracefully();

        // kill channels
        registeredChannels.forEach(NettyConnection::close);

        return Optional.empty();
    }
}

From source file:at.yawk.dbus.protocol.codec.BodyDecoder.java

@Override
protected void decode(ChannelHandlerContext ctx, AlignableByteBuf in, List<Object> out) throws Exception {
    MessageHeader header = ctx.channel().attr(Local.CURRENT_HEADER).get();
    if (header == null) {
        // message should be skipped
        return;//from   w w w.j ava2 s.  c  o m
    }

    DbusObject signature = header.getHeaderFields().get(HeaderField.SIGNATURE);
    if (signature == null) {
        throw new DecoderException("Non-empty body but missing signature header");
    }

    List<TypeDefinition> types = signature.typeValue();
    List<DbusObject> bodyObjects = new ArrayList<>();

    for (TypeDefinition type : types) {
        DbusObject object = type.deserialize(in);
        bodyObjects.add(object);

        log.trace("Decoded object {}", object);
    }

    MessageBody body = new MessageBody();
    body.setArguments(bodyObjects);
    out.add(body);
}

From source file:at.yawk.dbus.protocol.codec.IncomingMessageAdapter.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Attribute<MessageHeader> headerAttribute = ctx.channel().attr(Local.CURRENT_HEADER);
    if (msg instanceof MessageHeader) {
        if (((MessageHeader) msg).getMessageBodyLength() == 0) {
            DbusMessage message = new DbusMessage();
            message.setHeader((MessageHeader) msg);
            consumer.accept(message);//from w w  w  . ja  v  a 2 s. c o m
        } else {
            if (consumer.requireAccept((MessageHeader) msg)) {
                headerAttribute.set((MessageHeader) msg);
            } else {
                headerAttribute.set(null);
            }
        }
    } else if (msg instanceof MessageBody) {
        MessageHeader header = headerAttribute.get();
        if (header != null) {
            DbusMessage message = new DbusMessage();
            message.setHeader(header);
            message.setBody((MessageBody) msg);
            consumer.accept(message);
            headerAttribute.set(null);
        }
    } else {
        log.warn("Did not handle {}", msg);
    }
}

From source file:at.yawk.votifier.VotifierServerImpl.java

License:Mozilla Public License

public void init() {
    if (!initialized.compareAndSet(false, true)) {
        return;//from  w w w. j  a v  a2  s.  c o m
    }

    logger.info("Initializing votifier server...");
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                    logger.fine("Client disconnected.");
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    handleError(cause);
                }

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new VoteDecrypter(key)).addLast(new LineSplitter())
                            .addLast(new VoteDecoder()).addLast(new VersionEncoder())
                            .addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg)
                                        throws Exception {
                                    if (!(msg instanceof Operation)) {
                                        return;
                                    }
                                    Operation operation = (Operation) msg;
                                    if (operation.getOperation().equals("VOTE")) {
                                        listener.accept(
                                                new VoteEvent(operation.getUsername(), operation.getService(),
                                                        operation.getAddress(), operation.getTimestamp()));
                                        ctx.channel().close();
                                    } else {
                                        throw new UnsupportedOperationException(operation.getOperation());
                                    }
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                        throws Exception {
                                    handleError(cause);
                                }
                            });

                    logger.info("Client connected: Sending version packet.");
                    ch.writeAndFlush(version);
                }
            });
}

From source file:be.yildizgames.module.network.netty.client.AbstractClientMessageHandler.java

License:MIT License

@Override
public final void channelInactive(final ChannelHandlerContext ctx) throws Exception {
    super.channelInactive(ctx);
    this.callBack.connectionFailed();
    LOGGER.info("Netty channel closed: {}", ctx.channel());
}

From source file:be.yildizgames.module.network.netty.client.AbstractClientMessageHandler.java

License:MIT License

@Override
public final void exceptionCaught(final ChannelHandlerContext ctx, final Throwable e) {
    LOGGER.error("Exception", e);
    ctx.channel().close();
    callBack.connectionLost();/*from   w  ww .ja v a2s . c o  m*/
}

From source file:be.yildizgames.module.network.netty.client.SimpleWebSocketClientHandler.java

License:MIT License

@Override
public void channelActive(ChannelHandlerContext ctx) throws URISyntaxException {
    String host = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
    int port = ((InetSocketAddress) ctx.channel().remoteAddress()).getPort();
    String uri = "ws://" + host + ":" + port + "/websocket";
    this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(new URI(uri), WebSocketVersion.V13, null,
            false, new DefaultHttpHeaders());
    this.handshaker.handshake(ctx.channel());
}

From source file:be.yildizgames.module.network.netty.client.SimpleWebSocketClientHandler.java

License:MIT License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object received) {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        if (!(received instanceof FullHttpResponse)) {
            LOGGER.warn("Receiving message before handshake complete: {}", received);
            return;
        }//w  w  w .j  ava2  s .com
        FullHttpResponse handshake = FullHttpResponse.class.cast(received);
        LOGGER.debug("Handshake received: {}", handshake);
        handshaker.finishHandshake(ch, handshake);
        LOGGER.debug("Handshake complete.");
        handshakeFuture.setSuccess();
        this.callBack.handShakeComplete();
        return;
    }

    if (received instanceof TextWebSocketFrame) {
        String message = TextWebSocketFrame.class.cast(received).text();
        LOGGER.debug("Textframe received: {}", message);
        this.handleMessage(message);
    } else if (received instanceof CloseWebSocketFrame) {
        ch.close();
    }
}