List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead
@Override ChannelHandlerContext fireChannelRead(Object msg);
From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceQueryPacketAssembler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { log.trace("SourcePacketHandler.channelRead() : START"); try {/*from w w w . j a v a 2 s . c o m*/ //Make sure we are only receiving an instance of DatagramPacket if (!(msg instanceof DatagramPacket)) { return; } final DatagramPacket packet = (DatagramPacket) msg; final ByteBuf data = ((DatagramPacket) msg).content(); //Verify size if (data.readableBytes() <= 5) { log.debug( "Not a valid datagram for processing. Size getTotalRequests needs to be at least more than or equal to 5 bytes. Discarding. (Readable Bytes: {})", data.readableBytes()); return; } //Try to read protocol header, determine if its a single packet or a split-packet int protocolHeader = data.readIntLE(); //If the packet arrived is single type, we can already forward it to the next handler if (protocolHeader == 0xFFFFFFFF) { //Pass the message to the succeeding handlers ctx.fireChannelRead(packet.retain()); return; } //If the packet is a split type...we need to process each succeeding read until we have a complete packet else if (protocolHeader == 0xFFFFFFFE) { final ByteBuf reassembledPacket = processSplitPackets(data, ctx.channel().alloc(), packet.sender()); //Check if we already have a reassembled packet if (reassembledPacket != null) { ctx.fireChannelRead(packet.replace(reassembledPacket)); return; } } //Packet is not being handled by any of our processors, discard else { log.debug("Not a valid protocol header. Discarding. (Header Received: Dec = {}, Hex = {})", protocolHeader, Integer.toHexString(protocolHeader)); return; } } catch (Exception e) { log.error(String.format("Error while processing packet for %s", ((DatagramPacket) msg).sender()), e); throw e; } finally { //Release the message ReferenceCountUtil.release(msg); } log.trace("SourcePacketHandler.channelRead() : END"); }
From source file:com.irh.material.basics.netty.chapter14_1.server.LoginAuthRespHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage) msg; // ?????//from ww w . j ava 2 s . c o m 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:com.jansegre.jwar.webapi.FileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { request.retain();/* w ww . j a va 2s. co m*/ if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST); ctx.fireChannelRead(request); return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); ctx.fireChannelRead(request); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); ctx.fireChannelRead(request); return; } //XXX: notice hardcoded socket.io namespace if (uri.startsWith("/socket.io")) { ctx.fireChannelRead(request); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { File index_file = new File(sanitizeUri(uri + INDEX_FILE)); if (index_file.exists()) { file = index_file; } else { sendListing(ctx, file); return; } } else { sendRedirect(ctx, uri + '/'); return; } } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; if (useSendFile) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); } else { sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise()); } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println("Transfer progress: " + progress); } else { System.err.println("Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.err.println("Transfer complete."); } }); // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.jjzhk.Chapter14.netty.HeartBeatReqHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage) msg; if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) { heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS); } else if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) { System.out.println("Client receive server heart beat message : ---> " + message); } else/* w ww . j a va2 s .c o m*/ ctx.fireChannelRead(msg); }
From source file:com.jjzhk.Chapter14.netty.HeartBeatRespHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage) msg; if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) { System.out.println("Receive client heart beat message : ---> " + message); NettyMessage heartBeat = buildHeatBeat(); System.out.println("Send heart beat response message to client : ---> " + heartBeat); ctx.writeAndFlush(heartBeat);/*from w w w . j a va 2 s.c om*/ } else ctx.fireChannelRead(msg); }
From source file:com.jjzhk.Chapter14.netty.LoginAuthReqHandler.java
License:Apache License
/** * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to * the next {@link ChannelHandler} in the {@link ChannelPipeline}. * /*from w ww . ja v a2 s . co 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_RESP.value()) { byte loginResult = (Byte) message.getBody(); if (loginResult != (byte) 0) { ctx.close(); } else { System.out.println("Login is ok : " + message); ctx.fireChannelRead(msg); } } else ctx.fireChannelRead(msg); }
From source file:com.jjzhk.Chapter14.netty.LoginAuthRespHandler.java
License:Apache License
/** * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to * the next {@link ChannelHandler} in the {@link ChannelPipeline}. * /*from w w w. jav a2 s.co 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:com.jroossien.boxx.util.protocol.TinyProtocol.java
License:Open Source License
private void createServerChannelHandler() { // Handle connected channels endInitProtocol = new ChannelInitializer<Channel>() { @Override//from w ww . j a v a 2s . com protected void initChannel(Channel channel) throws Exception { try { // This can take a while, so we need to stop the main thread from interfering synchronized (networkManagers) { // Stop injecting channels if (!closed) { injectChannelInternal(channel); } } } catch (Exception e) { plugin.getLogger().log(Level.SEVERE, "Cannot inject incomming channel " + channel, e); } } }; // This is executed before Minecraft's channel handler beginInitProtocol = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { channel.pipeline().addLast(endInitProtocol); } }; serverChannelHandler = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Channel channel = (Channel) msg; // Prepare to initialize ths channel channel.pipeline().addFirst(beginInitProtocol); ctx.fireChannelRead(msg); } }; }
From source file:com.lampard.netty4.protocol.netty.client.HeartBeatReqHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage) msg; // ?????//from w w w . jav a2 s . c o m if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) { heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS); } else if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) { LOG.info("Client receive server heart beat message : ---> " + message); } else ctx.fireChannelRead(msg); }
From source file:com.lampard.netty4.protocol.netty.client.LoginAuthReqHandler.java
License:Apache License
/** * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to * the next {@link ChannelHandler} in the {@link ChannelPipeline}. * <p/>/*from w ww . j av a 2 s . 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_RESP.value()) { byte loginResult = (byte) message.getBody(); if (loginResult != (byte) 0) { // ? ctx.close(); } else { LOG.info("Login is ok : " + message); ctx.fireChannelRead(msg); } } else ctx.fireChannelRead(msg); }