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:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) {
    logger.debug("Channel Inactive");
    if (this.closed) {
        closeChannelAndEventLoop(ctx.channel());
        return;// w ww. jav  a  2 s.  co m
    }

    // debugSessions();

    Set s = sessionReplicaToClient.entrySet();
    Iterator i = s.iterator();
    while (i.hasNext()) {
        Entry m = (Entry) i.next();
        NettyClientServerSession value = (NettyClientServerSession) m.getValue();
        if (ctx.channel().equals(value.getChannel())) {
            int key = (Integer) m.getKey();
            toRemove(key);
            break;
        }
    }

    logger.debug("Session Closed, active clients=" + sessionReplicaToClient.size());
}

From source file:bftsmart.communication.client.netty.NettyTOMMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> list) throws Exception {

    // Wait until the length prefix is available.
    if (buffer.readableBytes() < Integer.BYTES) {
        return;/*w w  w.  j  a  v  a  2  s  .  co  m*/
    }

    int dataLength = buffer.getInt(buffer.readerIndex());

    //Logger.println("Receiving message with "+dataLength+" bytes.");

    // Wait until the whole data is available.
    if (buffer.readableBytes() < dataLength + Integer.BYTES) {
        return;
    }

    // Skip the length field because we know it already.
    buffer.skipBytes(Integer.BYTES);

    int size = buffer.readInt();
    byte[] data = new byte[size];
    buffer.readBytes(data);

    byte[] signature = null;
    size = buffer.readInt();

    if (size > 0) {
        signature = new byte[size];
        buffer.readBytes(signature);
    }

    DataInputStream dis = null;
    TOMMessage sm = null;

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        dis = new DataInputStream(bais);
        sm = new TOMMessage();
        sm.rExternal(dis);
        sm.serializedMessage = data;

        if (signature != null) {
            sm.serializedMessageSignature = signature;
            sm.signed = true;
        }

        if (!isClient) {
            rl.readLock().lock();
            if (!sessionTable.containsKey(sm.getSender())) {
                rl.readLock().unlock();

                NettyClientServerSession cs = new NettyClientServerSession(context.channel(), sm.getSender());

                rl.writeLock().lock();
                sessionTable.put(sm.getSender(), cs);
                logger.debug("Active clients: " + sessionTable.size());
                rl.writeLock().unlock();

            } else {
                rl.readLock().unlock();
            }
        }
        logger.debug("Decoded reply from " + sm.getSender() + " with sequence number " + sm.getSequence());
        list.add(sm);
    } catch (Exception ex) {

        logger.error("Failed to decode TOMMessage", ex);
    }
    return;
}

From source file:books.netty.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();/*from   ww  w . j av  a 2 s.co m*/
    if (ctx.channel().isActive()) {
        sendError(ctx, INTERNAL_SERVER_ERROR);
    }
}

From source file:books.netty.protocol.netty.server.LoginAuthRespHandler.java

License:Apache License

/**
 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to
 * the next {@link ChannelHandler} in the {@link ChannelPipeline}.
 * <p>/*from w  w w  . j ava2s .  c o  m*/
 * Sub-classes may override this method to change behavior.
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    // ?????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
        String nodeIndex = ctx.channel().remoteAddress().toString();
        NettyMessage loginResp = null;
        // ???
        if (nodeCheck.containsKey(nodeIndex)) {
            loginResp = buildResponse((byte) -1);
        } else {
            InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
            String ip = address.getAddress().getHostAddress();
            boolean isOK = false;
            for (String WIP : whitekList) {
                if (WIP.equals(ip)) {
                    isOK = true;
                    break;
                }
            }
            loginResp = isOK ? buildResponse((byte) 0) : buildResponse((byte) -1);
            if (isOK)
                nodeCheck.put(nodeIndex, true);
        }
        System.out.println("The login response is : " + loginResp + " body [" + loginResp.getBody() + "]");
        ctx.writeAndFlush(loginResp);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:books.netty.protocol.netty.server.LoginAuthRespHandler.java

License:Apache License

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();/*from  w  w  w .  j  ava 2  s.com*/
    nodeCheck.remove(ctx.channel().remoteAddress().toString());// 
    ctx.close();
    ctx.fireExceptionCaught(cause);
}

From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {

    // HTTP?HHTP/*from ww w  .j av  a 2  s  . co m*/
    if (!req.getDecoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;
    }

    // ??
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            "ws://localhost:8080/websocket", null, false);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // ?/*from   www  . j  av  a2  s  .  co  m*/
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    // ?Ping?
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    // ?????
    if (!(frame instanceof TextWebSocketFrame)) {
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", frame.getClass().getName()));
    }

    // ?
    String request = ((TextWebSocketFrame) frame).text();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format("%s received %s", ctx.channel(), request));
    }
    ctx.channel().write(new TextWebSocketFrame(request
            + " , Netty WebSocket?" + new java.util.Date().toString()));
}

From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // /*from   w ww  . j a va 2  s.  c  o  m*/
    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());
    }

    // ?Keep-Alive
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:books.netty.ssl.SecureChatServerHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to
    // the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override//from  w  w  w  .j a va 2s  . c om
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    ctx.writeAndFlush("Your session is protected by "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");

                    channels.add(ctx.channel());
                }
            });
}

From source file:books.netty.ssl.SecureChatServerHandler.java

License:Apache License

public void messageReceived(ChannelHandlerContext ctx, String msg) {
    // Send the received message to all channels but the current one.
    for (Channel c : channels) {
        if (c != ctx.channel()) {
            c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
        } else {//from  ww  w.j  ava  2  s.c o  m
            c.writeAndFlush("[you] " + msg + '\n');
        }
    }

    // Close the connection if the client has sent 'bye'.
    if ("bye".equals(msg.toLowerCase())) {
        ctx.close();
    }
}