@Override protected Object filterOutboundMessage(Object msg) { if (msg instanceof DatagramPacket) { DatagramPacket p = (DatagramPacket) msg; ByteBuf content = p.content(); if (isSingleDirectBuffer(content)) { return p; } return new DatagramPacket(newDirectBuffer(p, content), p.recipient()); } if (msg instanceof ByteBuf) { ByteBuf buf = (ByteBuf) msg; if (isSingleDirectBuffer(buf)) { return buf; } return newDirectBuffer(buf); } if (msg instanceof AddressedEnvelope) { @SuppressWarnings("unchecked") AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg; if (e.content() instanceof ByteBuf) { ByteBuf content = (ByteBuf) e.content(); if (isSingleDirectBuffer(content)) { return e; } return new DefaultAddressedEnvelope<ByteBuf, SocketAddress>( newDirectBuffer(e, content), e.recipient()); } } throw new UnsupportedOperationException( "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES); }
@Override protected void channelRead0( ChannelHandlerContext ctx, io.netty.channel.socket.DatagramPacket message) throws Exception { byte[] bytes = new byte[message.content().readableBytes()]; message.content().readBytes(bytes); obs.onNext(bytes); }
@Override public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { String req = packet.content().toString(CharsetUtil.UTF_8); System.out.println(req); if ("谚语字典查询?".equals(req)) { ctx.writeAndFlush( new DatagramPacket( Unpooled.copiedBuffer("谚语查询结果: " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } }
@Override public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { String udpContentString = packet.content().toString(CharsetUtil.UTF_8); long currentTimestampInMilliseconds = System.currentTimeMillis(); List<GraphiteMetric> graphiteMetrics = GraphiteMetric.parseGraphiteMetrics( udpContentString, GlobalVariables.graphiteAggregatedPrefix, currentTimestampInMilliseconds); for (GraphiteMetric graphiteMetric : graphiteMetrics) { long hashKey = GlobalVariables.metricHashKeyGenerator.incrementAndGet(); graphiteMetric.setHashKey(hashKey); if (graphiteMetric.getMetricPath() != null) graphiteMetric.getMetricPath().hashCode(); GlobalVariables.graphiteAggregatorMetrics.put(graphiteMetric.getHashKey(), graphiteMetric); GlobalVariables.incomingMetricsCount.incrementAndGet(); } if (ApplicationConfiguration.isDebugModeEnabled()) { logger.info("UDP_Graphite_Aggregator_Received_Metrics=" + graphiteMetrics.size()); logger.info("UDP_Graphite_Aggregator_String=\"" + udpContentString + "\""); } }
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { String response = msg.content().toString(CharsetUtil.UTF_8); if (response.startsWith("QOTM: ")) { System.out.println("Quote of the Moment: " + response.substring(6)); ctx.close(); } }
@Override protected int doWriteMessages(MessageBuf<Object> buf, boolean lastSpin) throws Exception { DatagramPacket packet = (DatagramPacket) buf.peek(); ByteBuf data = packet.data(); int dataLen = data.readableBytes(); ByteBuffer nioData; if (data.nioBufferCount() == 1) { nioData = data.nioBuffer(); } else { nioData = ByteBuffer.allocate(dataLen); data.getBytes(data.readerIndex(), nioData); nioData.flip(); } final int writtenBytes = javaChannel().send(nioData, packet.remoteAddress()); final SelectionKey key = selectionKey(); final int interestOps = key.interestOps(); if (writtenBytes <= 0 && dataLen > 0) { // Did not write a packet. // 1) If 'lastSpin' is false, the caller will call this method again real soon. // - Do not update OP_WRITE. // 2) If 'lastSpin' is true, the caller will not retry. // - Set OP_WRITE so that the event loop calls flushForcibly() later. if (lastSpin) { if ((interestOps & SelectionKey.OP_WRITE) == 0) { key.interestOps(interestOps | SelectionKey.OP_WRITE); } } return 0; } // Wrote a packet. buf.remove(); // packet was written free up buffer packet.free(); if (buf.isEmpty()) { // Wrote the outbound buffer completely - clear OP_WRITE. if ((interestOps & SelectionKey.OP_WRITE) != 0) { key.interestOps(interestOps & ~SelectionKey.OP_WRITE); } } return 1; }
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { String request = packet.content().toString(CharsetUtil.UTF_8); if (logger.isDebugEnabled()) logger.debug("Sender " + packet.sender() + " sent request:" + request); if (!sessionList.inverse().containsKey(packet.sender())) { String session = UUID.randomUUID().toString(); String localAddress = ctx.channel().localAddress().toString(); String remoteAddress = ctx.channel().remoteAddress().toString(); SubscriptionManagerFactory.getInstance() .add(session, session, outputType, localAddress, remoteAddress); sessionList.put(session, packet.sender()); if (logger.isDebugEnabled()) logger.debug("Added Sender " + packet.sender() + ", session:" + session); ctx.channel() .writeAndFlush( new DatagramPacket( Unpooled.copiedBuffer( Util.getWelcomeMsg().toString() + "\r\n", CharsetUtil.UTF_8), packet.sender())); } Map<String, Object> headers = getHeaders(sessionList.inverse().get(packet.sender())); producer.sendBodyAndHeaders(request, headers); }
@Override protected void doWriteMessages(MessageBuf<Object> buf) throws Exception { DatagramPacket p = (DatagramPacket) buf.poll(); ByteBuf data = p.data(); int length = data.readableBytes(); InetSocketAddress remote = p.remoteAddress(); if (remote != null) { tmpPacket.setSocketAddress(remote); } if (data.hasArray()) { tmpPacket.setData(data.array(), data.arrayOffset() + data.readerIndex(), length); } else { byte[] tmp = new byte[length]; data.getBytes(data.readerIndex(), tmp); tmpPacket.setData(tmp); } socket.send(tmpPacket); }
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { ByteBuf in = msg.content(); if (in.readUnsignedByte() != 0xFE || in.readUnsignedByte() != 0xFD) { bungee.getLogger().log(Level.WARNING, "Query - Incorrect magic!: {0}", msg.sender()); return; } ByteBuf out = ctx.alloc().buffer(); AddressedEnvelope response = new DatagramPacket(out, msg.sender()); byte type = in.readByte(); int sessionId = in.readInt(); if (type == 0x09) { out.writeByte(0x09); out.writeInt(sessionId); int challengeToken = random.nextInt(); sessions.put(challengeToken, System.currentTimeMillis()); writeNumber(out, challengeToken); } if (type == 0x00) { int challengeToken = in.readInt(); Long session = sessions.get(challengeToken); if (session == null || System.currentTimeMillis() - session > TimeUnit.SECONDS.toMillis(30)) { throw new IllegalStateException("No session!"); } out.writeByte(0x00); out.writeInt(sessionId); if (in.readableBytes() == 0) { // Short response writeString(out, listener.getMotd()); // MOTD writeString(out, "SMP"); // Game Type writeString(out, "BungeeCord_Proxy"); // World Name writeNumber(out, bungee.getOnlineCount()); // Online Count writeNumber(out, listener.getMaxPlayers()); // Max Players writeShort(out, listener.getHost().getPort()); // Port writeString(out, listener.getHost().getHostString()); // IP } else if (in.readableBytes() == 4) { // Long Response out.writeBytes( new byte[] {0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00}); Map<String, String> data = new LinkedHashMap<>(); data.put("hostname", listener.getMotd()); data.put("gametype", "SMP"); // Start Extra Info data.put("game_id", "MINECRAFT"); data.put("version", bungee.getGameVersion()); data.put("plugins", ""); // End Extra Info data.put("map", "BungeeCord"); // data.put( "numplayers", Integer.toString( bungee.getOnlineCount() ) ); data.put("numplayers", Integer.toString(getFakePlayerNumber())); data.put("maxplayers", Integer.toString(listener.getMaxPlayers())); data.put("hostport", Integer.toString(listener.getHost().getPort())); data.put("hostip", listener.getHost().getHostString()); for (Map.Entry<String, String> entry : data.entrySet()) { writeString(out, entry.getKey()); writeString(out, entry.getValue()); } out.writeByte(0x00); // Null // Padding writeString(out, "\01player_\00"); // Player List for (ProxiedPlayer p : bungee.getPlayers()) { writeString(out, p.getName()); } // writeString( out, "Mr_ludek" ); // for(int x = 0; x < getFakePlayerNumber(); x++){ // } writePlayers(getFakePlayerNumber(), out); out.writeByte(0x00); // Null } else { // Error! throw new IllegalStateException("Invalid data request packet"); } } ctx.writeAndFlush(response); }
@Override public DatagramPacket encode(DatagramPacket dg) { dg.content().writeByte(getPacketID()); writeString(dg.content(), message); return dg; }
@Override public void decode(DatagramPacket dg, ChannelHandlerContext ctx) { message = readString(dg.content()); }
@Override protected void handleIncoming(DatagramPacket msg) { receiveMessage(msg.sender(), msg.content().nioBuffer()); }