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: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/*  w ww  .  j  a va  2  s .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:SecureChatServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    // 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 {//  www  .  j av a 2s .  c o  m
            c.writeAndFlush("[you] " + msg + '\n');
        }
    }

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

From source file:HttpUploadServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);/* ww w .  j  a v a  2s  . co m*/
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : headers) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                readHttpDataAllReceive(ctx.channel());
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}

From source file:HttpUploadServerHandler.java

License:Apache License

private void writeMenu(ChannelHandlerContext ctx) {
    // print several HTML forms
    // Convert the response content to a ChannelBuffer.
    responseContent.setLength(0);/*  w  ww  .j  a va2  s .  c o  m*/

    // create Pseudo Menu
    responseContent.append("<html>");
    responseContent.append("<head>");
    responseContent.append("<title>Netty Test Form</title>\r\n");
    responseContent.append("</head>\r\n");
    responseContent.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>");

    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr>");
    responseContent.append("<td>");
    responseContent.append("<h1>Netty Test Form</h1>");
    responseContent.append("Choose one FORM");
    responseContent.append("</td>");
    responseContent.append("</tr>");
    responseContent.append("</table>\r\n");

    // GET
    responseContent.append("<CENTER>GET FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent.append("<FORM ACTION=\"/formget\" METHOD=\"GET\">");
    responseContent.append("<input type=hidden name=getform value=\"GET\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    // POST
    responseContent.append("<CENTER>POST FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent.append("<FORM ACTION=\"/formpost\" METHOD=\"POST\">");
    responseContent.append("<input type=hidden name=getform value=\"POST\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("<tr><td>Fill with file (only file name will be transmitted): <br> "
            + "<input type=file name=\"myfile\">");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    // POST with enctype="multipart/form-data"
    responseContent.append("<CENTER>POST MULTIPART FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent
            .append("<FORM ACTION=\"/formpostmultipart\" ENCTYPE=\"multipart/form-data\" METHOD=\"POST\">");
    responseContent.append("<input type=hidden name=getform value=\"POST\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("<tr><td>Fill with file: <br> <input type=file name=\"myfile\">");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    responseContent.append("</body>");
    responseContent.append("</html>");

    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);

    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    response.headers().set(CONTENT_LENGTH, String.valueOf(buf.readableBytes()));

    // Write the response.
    ctx.channel().write(response);
}

From source file:HttpUploadServerHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    logger.log(Level.WARNING, responseContent.toString(), cause);
    ctx.channel().close();
}

From source file:WebSocketFrameHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {

    if (frame instanceof TextWebSocketFrame) {
        String inboundMessage = ((TextWebSocketFrame) frame).text();
        Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());

        //Message to be sent.
        String Echo = "Timestamp: " + currentTimestamp + " " + ctx.channel().toString() + "\n" + "Server tag: "
                + tag + "Server tag: " + tag + " -- Text: " + inboundMessage;

        System.out.println(Echo); //same message to server's out
        ctx.channel().writeAndFlush(new TextWebSocketFrame(Echo));

    } else {//from   w ww  .j  a  v  a2 s.c  o m
        String message = "Unsupported frame type: " + frame.getClass().getName();
        throw new UnsupportedOperationException(message);
    }

}

From source file:WorldClockClientHandler.java

License:Apache License

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    channel = ctx.channel();
}

From source file:NettyServer.java

License:Open Source License

void start() throws Exception {
    parentGroup = new NioEventLoopGroup(1);
    childGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap().group(parentGroup, childGroup)
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*w  w w  . ja va 2 s . c  o m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();

                    pipeline.addLast("lineFrame", new LineBasedFrameDecoder(256));
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast("encoder", new StringEncoder());

                    pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            Channel channel = ctx.channel();
                            channelActiveHandler.accept(channel);
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            messageConsumer.accept(msg);
                        }
                    });
                }
            });
    channel = bootstrap.bind(port).channel();
    System.out.println("NettyServer started");
}

From source file:HttpUploadClientHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.channel().close();
}

From source file:NettyInboundHttpTargetHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    //   System.out.println("Receving data");
    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override// w w w  .  ja  v a2 s . co m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                ctx.channel().read();
            } else {
                future.channel().close();
            }
        }
    });
}