List of usage examples for io.netty.buffer ByteBuf isReadable
public abstract boolean isReadable();
From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { send100Continue(ctx);/*from ww w . j ava 2s .com*/ } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(request.headers().get(HttpHeaderNames.HOST, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { CharSequence key = h.getKey(); CharSequence value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (CharSequence name : trailer.trailingHeaders().names()) { for (CharSequence value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out, HttpResponse res) { channel.write(res);//from ww w. ja v a 2s . c o m if (log.isTraceEnabled()) { log.trace("Out message: {} - sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId()); } if (out.isReadable()) { channel.write(out); } else { out.release(); } channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE); }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void handleWebsocket(final OutPacketMessage msg, ChannelHandlerContext ctx) throws IOException { while (true) { Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport()); Packet packet = queue.poll();//from w w w. jav a2s .c o m if (packet == null) { break; } final ByteBuf out = encoder.allocateBuffer(ctx.alloc()); encoder.encodePacket(packet, out, ctx.alloc(), true); WebSocketFrame res = new TextWebSocketFrame(out); if (log.isTraceEnabled()) { log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId()); } if (out.isReadable()) { ctx.channel().writeAndFlush(res); } else { out.release(); } for (ByteBuf buf : packet.getAttachments()) { ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc()); outBuf.writeByte(4); outBuf.writeBytes(buf); if (log.isTraceEnabled()) { log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId()); } ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf)); } } }
From source file:com.corundumstudio.socketio.handler.InPacketHandler.java
License:Apache License
@Override protected void channelRead0(io.netty.channel.ChannelHandlerContext ctx, PacketsMessage message) throws Exception { ByteBuf content = message.getContent(); ClientHead client = message.getClient(); if (log.isTraceEnabled()) { log.trace("In message: {} sessionId: {}", content.toString(CharsetUtil.UTF_8), client.getSessionId()); }/* www.j ava 2 s . co m*/ while (content.isReadable()) { try { Packet packet = decoder.decodePackets(content, client); if (packet.hasAttachments() && !packet.isAttachmentsLoaded()) { return; } Namespace ns = namespacesHub.get(packet.getNsp()); if (ns == null) { if (packet.getSubType() == PacketType.CONNECT) { Packet p = new Packet(PacketType.MESSAGE); p.setSubType(PacketType.ERROR); p.setNsp(packet.getNsp()); p.setData("Invalid namespace"); client.send(p); return; } log.debug("Can't find namespace for endpoint: {}, sessionId: {} probably it was removed.", packet.getNsp(), client.getSessionId()); return; } if (packet.getSubType() == PacketType.CONNECT) { client.addNamespaceClient(ns); } NamespaceClient nClient = client.getChildClient(ns); if (nClient == null) { log.debug( "Can't find namespace client in namespace: {}, sessionId: {} probably it was disconnected.", ns.getName(), client.getSessionId()); return; } packetListener.onPacket(packet, nClient, message.getTransport()); } catch (Exception ex) { String c = content.toString(CharsetUtil.UTF_8); log.error( "Error during data processing. Client sessionId: " + client.getSessionId() + ", data: " + c, ex); throw ex; } } }
From source file:com.corundumstudio.socketio.handler.PacketHandler.java
License:Apache License
@Override protected void channelRead0(io.netty.channel.ChannelHandlerContext ctx, PacketsMessage message) throws Exception { ByteBuf content = message.getContent(); MainBaseClient client = message.getClient(); if (log.isTraceEnabled()) { log.trace("In message: {} sessionId: {}", content.toString(CharsetUtil.UTF_8), client.getSessionId()); }/* w w w. ja v a 2 s.c om*/ while (content.isReadable()) { try { Packet packet = decoder.decodePackets(content, client.getSessionId()); Namespace ns = namespacesHub.get(packet.getEndpoint()); if (ns == null) { log.debug("Can't find namespace for endpoint: {}, sessionId: {} probably it was removed.", packet.getEndpoint(), client.getSessionId()); return; } if (packet.getType() == PacketType.CONNECT) { client.addChildClient(ns); } NamespaceClient nClient = (NamespaceClient) client.getChildClient(ns); if (nClient == null) { log.debug( "Can't find namespace client in namespace: {}, sessionId: {} probably it was disconnected.", ns.getName(), client.getSessionId()); return; } packetListener.onPacket(packet, nClient); } catch (Exception ex) { String c = content.toString(CharsetUtil.UTF_8); log.error( "Error during data processing. Client sessionId: " + client.getSessionId() + ", data: " + c, ex); return; } } }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private Packet decodePacket(ByteBuf buffer, UUID uuid) throws IOException { if (buffer.readableBytes() < 3) { throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8)); }/*from w w w. ja v a 2 s.c om*/ PacketType type = getType(buffer); int readerIndex = buffer.readerIndex() + 1; // 'null' to avoid unnecessary StringBuilder creation boolean hasData = false; StringBuilder messageId = null; for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) { if (messageId == null) { messageId = new StringBuilder(4); } byte msg = buffer.getByte(readerIndex); if (msg == Packet.SEPARATOR) { break; } if (msg != (byte) '+') { messageId.append((char) msg); } else { hasData = true; } } Long id = null; if (messageId != null && messageId.length() > 0) { id = Long.valueOf(messageId.toString()); } // 'null' to avoid unnecessary StringBuilder creation StringBuilder endpointBuffer = null; for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) { if (endpointBuffer == null) { endpointBuffer = new StringBuilder(); } byte msg = buffer.getByte(readerIndex); if (msg == Packet.SEPARATOR) { break; } endpointBuffer.append((char) msg); } String endpoint = Namespace.DEFAULT_NAME; if (endpointBuffer != null && endpointBuffer.length() > 0) { endpoint = endpointBuffer.toString(); } if (buffer.readableBytes() == readerIndex) { buffer.readerIndex(buffer.readableBytes()); } else { readerIndex += 1; buffer.readerIndex(readerIndex); } Packet packet = new Packet(type); packet.setEndpoint(endpoint); if (id != null) { packet.setId(id); if (hasData) { packet.setAck(Packet.ACK_DATA); } else { packet.setAck(true); } } switch (type) { case ERROR: { if (!buffer.isReadable()) { break; } String[] pieces = buffer.toString(CharsetUtil.UTF_8).split("\\+"); if (pieces.length > 0 && pieces[0].trim().length() > 0) { ErrorReason reason = ErrorReason.valueOf(Integer.valueOf(pieces[0])); packet.setReason(reason); if (pieces.length > 1) { ErrorAdvice advice = ErrorAdvice.valueOf(Integer.valueOf(pieces[1])); packet.setAdvice(advice); } } break; } case MESSAGE: { if (buffer.isReadable()) { packet.setData(buffer.toString(CharsetUtil.UTF_8)); } else { packet.setData(""); } break; } case EVENT: { ByteBufInputStream in = new ByteBufInputStream(buffer); Event event = jsonSupport.readValue(in, Event.class); packet.setName(event.getName()); if (event.getArgs() != null) { packet.setArgs(event.getArgs()); } break; } case JSON: { ByteBufInputStream in = new ByteBufInputStream(buffer); JsonObject obj = jsonSupport.readValue(in, JsonObject.class); if (obj != null) { packet.setData(obj.getObject()); } else { in.reset(); Object object = jsonSupport.readValue(in, Object.class); packet.setData(object); } break; } case CONNECT: { if (buffer.isReadable()) { packet.setQs(buffer.toString(CharsetUtil.UTF_8)); } break; } case ACK: { if (!buffer.isReadable()) { break; } boolean validFormat = true; int plusIndex = -1; for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) { byte dataChar = buffer.getByte(i); if (!Character.isDigit(dataChar)) { if (dataChar == '+') { plusIndex = i; break; } else { validFormat = false; break; } } } if (!validFormat) { break; } if (plusIndex == -1) { packet.setAckId(parseLong(buffer)); break; } else { packet.setAckId(parseLong(buffer, plusIndex)); buffer.readerIndex(plusIndex + 1); ByteBufInputStream in = new ByteBufInputStream(buffer); AckCallback<?> callback = ackManager.getCallback(uuid, packet.getAckId()); AckArgs args = jsonSupport.readAckArgs(in, callback); packet.setArgs(args.getArgs()); } break; } case DISCONNECT: case HEARTBEAT: case NOOP: break; } buffer.readerIndex(buffer.readerIndex() + buffer.readableBytes()); return packet; }
From source file:com.corundumstudio.socketio.parser.PayloadTest.java
License:Apache License
@Test public void testPayloadDecode() throws IOException { ByteBuf buffer = Unpooled .wrappedBuffer("\ufffd5\ufffd3:::5\ufffd7\ufffd3:::53d\ufffd3\ufffd0::".getBytes()); List<Packet> payload = new ArrayList<Packet>(); while (buffer.isReadable()) { Packet packet = decoder.decodePackets(buffer, null); payload.add(packet);/*from ww w . ja va 2 s . c om*/ } Assert.assertEquals(3, payload.size()); Packet msg1 = payload.get(0); Assert.assertEquals(PacketType.MESSAGE, msg1.getType()); Assert.assertEquals("5", msg1.getData()); Packet msg2 = payload.get(1); Assert.assertEquals(PacketType.MESSAGE, msg2.getType()); Assert.assertEquals("53d", msg2.getData()); Packet msg3 = payload.get(2); Assert.assertEquals(PacketType.DISCONNECT, msg3.getType()); }
From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java
License:Apache License
private Packet decode(ClientHead head, ByteBuf frame) throws IOException { if ((frame.getByte(0) == 'b' && frame.getByte(1) == '4') || frame.getByte(0) == 4 || frame.getByte(0) == 1) {//from www .j a va2 s . c o m return parseBinary(head, frame); } PacketType type = readType(frame); Packet packet = new Packet(type); if (type == PacketType.PING) { packet.setData(readString(frame)); return packet; } if (!frame.isReadable()) { return packet; } PacketType innerType = readInnerType(frame); packet.setSubType(innerType); parseHeader(frame, packet, innerType); parseBody(head, frame, packet); return packet; }
From source file:com.corundumstudio.socketio.protocol.PacketEncoder.java
License:Apache License
private void processUtf8(ByteBuf in, ByteBuf out, boolean jsonpMode) { while (in.isReadable()) { short value = (short) (in.readByte() & 0xFF); if (value >>> 7 == 0) { if (jsonpMode && (value == '\\' || value == '\'')) { out.writeByte('\\'); }//from w ww . j a v a2 s .c o m out.writeByte(value); } else { out.writeByte(((value >>> 6) | 0xC0)); out.writeByte(((value & 0x3F) | 0x80)); } } }
From source file:com.corundumstudio.socketio.SocketIOEncoder.java
License:Apache License
private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out) { HttpResponse res = createHttpResponse(msg.getOrigin(), out); channel.write(res);//www . ja va2s . c o m if (log.isTraceEnabled()) { log.trace("Out message: {} - sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId()); } if (out.isReadable()) { channel.write(out); } else { out.release(); } ChannelFuture f = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); f.addListener(ChannelFutureListener.CLOSE); }