List of usage examples for io.netty.buffer Unpooled buffer
public static ByteBuf buffer()
From source file:com.whizzosoftware.hobson.radiora.api.codec.RadioRaFrameEncoderTest.java
License:Open Source License
@Test public void testZoneMapInquiryEncode() throws Exception { RadioRaFrameEncoder encoder = new RadioRaFrameEncoder(); ZoneMapInquiry zmpi = new ZoneMapInquiry(); ByteBuf buf = Unpooled.buffer(); encoder.encode(null, zmpi, buf);//w ww . j ava2 s . co m assertEquals("ZMPI\r", buf.toString(Charset.forName("UTF8"))); }
From source file:com.yogpc.mc_lib.APacketTile.java
License:Open Source License
@Override public final Packet getDescriptionPacket() { final ByteBuf buf = Unpooled.buffer(); buf.writeByte(0);// www.j a va 2 s.c o m new YogpstopPacket(this).writeData(buf); return new FMLProxyPacket(buf, "YogpstopLib"); }
From source file:dan200.QCraft.java
License:Open Source License
private static FMLProxyPacket encode(QCraftPacket packet) { ByteBuf buffer = Unpooled.buffer(); packet.toBytes(buffer);/*from ww w . j a v a 2s. c o m*/ return new FMLProxyPacket(buffer, "qCraft"); }
From source file:dbseer.middleware.server.MiddlewareServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { MiddlewarePacket packet = (MiddlewarePacket) msg; int header = packet.header; Log.debug("Child handler channel read header = " + header); if (server.getConnectedChannelGroup().size() > 0 && !server.getConnectedChannelGroup().contains(ctx.channel())) { // ByteBuf ans = Unpooled.buffer(); // ans.writeInt(MiddlewareConstants.PACKET_CONNECTION_DENIED); // ans.writeInt(0); // ctx.writeAndFlush(ans); MiddlewarePacket sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_CONNECTION_DENIED); ctx.writeAndFlush(sendPacket);//from www. ja va 2 s . c o m return; } if (server.getConnectedChannelGroup().size() == 0) { server.getConnectedChannelGroup().add(ctx.channel()); } if (header == MiddlewareConstants.PACKET_START_MONITORING) { Log.debug("start monitoring"); // check id and password String idPassword = packet.body; String[] tokens = idPassword.split("@", 2); String receivedId = tokens[0]; String receivedPassword = tokens[1]; // ByteBuf ans = Unpooled.buffer(); MiddlewarePacket sendPacket; if (!receivedId.equals(server.getId()) || !receivedPassword.equals(server.getPassword())) { Log.debug("start monitoring failure: authentication failed."); // ans.writeInt(MiddlewareConstants.PACKET_AUTHENTICATION_FAILURE); String reason = "Authentication failed: "; if (!receivedId.equals(server.getId())) { reason += "Invalid id."; } else if (!receivedPassword.equals(server.getPassword())) { reason += "Incorrect password."; } // ans.writeInt(reason.getBytes("UTF-8").length); // ans.writeBytes(reason.getBytes("UTF-8")); sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_AUTHENTICATION_FAILURE, reason); } else { // stop monitoring if it is running. server.stopMonitoring(); boolean isStarted; isStarted = server.startMonitoring(); if (isStarted) { Log.debug("start monitoring success"); // ans.writeInt(MiddlewareConstants.PACKET_START_MONITORING_SUCCESS); // ans.writeInt(0); sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_START_MONITORING_SUCCESS); } else { Log.debug("start monitoring failure"); // ans.writeInt(MiddlewareConstants.PACKET_START_MONITORING_FAILURE); // ans.writeInt(0); sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_START_MONITORING_FAILURE); } } // ctx.writeAndFlush(ans); ctx.writeAndFlush(sendPacket); } else if (header == MiddlewareConstants.PACKET_PING) { ByteBuf ans = Unpooled.buffer(); // ans.writeInt(MiddlewareConstants.PACKET_PING); // ans.writeInt(0); // ctx.writeAndFlush(ans); MiddlewarePacket sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_PING); ctx.writeAndFlush(sendPacket); } else if (header == MiddlewareConstants.PACKET_STOP_MONITORING) { Log.debug("stop monitoring"); // stop monitoring server.stopMonitoring(); // ByteBuf ans = Unpooled.buffer(); MiddlewarePacket sendPacket; // check monitoring if (server.isMonitoring()) { Log.debug("stop monitoring failure"); // ans.writeInt(MiddlewareConstants.PACKET_STOP_MONITORING_FAILURE); // ans.writeInt(0); sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_STOP_MONITORING_FAILURE); } else { Log.debug("stop monitoring success"); // ans.writeInt(MiddlewareConstants.PACKET_STOP_MONITORING_SUCCESS); // ans.writeInt(0); sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_STOP_MONITORING_SUCCESS); } // ctx.writeAndFlush(ans); ctx.writeAndFlush(sendPacket); } else if (header == MiddlewareConstants.PACKET_CHECK_VERSION) { String clientVersion = packet.body; MiddlewarePacket sendPacket; // ByteBuf ans = Unpooled.buffer(); if (clientVersion.equalsIgnoreCase(MiddlewareConstants.PROTOCOL_VERSION)) { // ans.writeInt(MiddlewareConstants.PACKET_CHECK_VERSION_SUCCESS); // ans.writeInt(0); sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_CHECK_VERSION_SUCCESS); } else { // ans.writeInt(MiddlewareConstants.PACKET_CHECK_VERSION_FAILURE); // ans.writeInt(MiddlewareConstants.PROTOCOL_VERSION.getBytes("UTF-8").length); // ans.writeBytes(MiddlewareConstants.PROTOCOL_VERSION.getBytes("UTF-8")); sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_CHECK_VERSION_FAILURE, MiddlewareConstants.PROTOCOL_VERSION); } // ctx.writeAndFlush(ans); ctx.writeAndFlush(sendPacket); Log.debug("check version sent"); } else if (header == MiddlewareConstants.PACKET_REQUEST_SERVER_LIST) { String serverList = server.getServerList(); // ByteBuf ans = Unpooled.buffer(); // ans.writeInt(MiddlewareConstants.PACKET_SERVER_LIST); // ans.writeInt(serverList.getBytes("UTF-8").length); // ans.writeBytes(serverList.getBytes("UTF-8")); // ctx.writeAndFlush(ans); MiddlewarePacket sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_SERVER_LIST, serverList); ctx.writeAndFlush(sendPacket); Log.debug("server list sent"); } else if (header == MiddlewareConstants.PACKET_REQUEST_TX_LOG) { // String log = ""; // ArrayList<String> logs = new ArrayList<String>(); // server.getDbLogQueue().drainTo(logs); // for (String aLog : logs) // { // log += aLog; // } String log = server.getDbLogListener().getString(); // ByteBuf ans = Unpooled.buffer(8 + log.getBytes("UTF-8").length); // ans.writeInt(MiddlewareConstants.PACKET_TX_LOG); // ans.writeInt(log.getBytes("UTF-8").length); // ans.writeBytes(log.getBytes("UTF-8")); // ctx.writeAndFlush(ans); MiddlewarePacket sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_TX_LOG, log); ctx.writeAndFlush(sendPacket); Log.debug("db log sent"); } else if (header == MiddlewareConstants.PACKET_REQUEST_SYS_LOG) { String serverStr = packet.body; String log = serverStr + MiddlewareConstants.SERVER_STRING_DELIMITER; // ArrayList<String> logs = new ArrayList<>(); // server.getServer(serverStr).getLogQueue().drainTo(logs); // for (String aLog : logs) // { // log += aLog; // } log += server.getServer(serverStr).getLogTailerListener().getString(); // ByteBuf ans = Unpooled.buffer(8 + log.getBytes("UTF-8").length); // ans.writeInt(MiddlewareConstants.PACKET_SYS_LOG); // ans.writeInt(log.getBytes("UTF-8").length); // ans.writeBytes(log.getBytes("UTF-8")); // ctx.writeAndFlush(ans); MiddlewarePacket sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_SYS_LOG, log); ctx.writeAndFlush(sendPacket); Log.debug("sys log sent"); } else if (header == MiddlewareConstants.PACKET_REQUEST_TABLE_COUNT) { String body = packet.body; String[] contents = body.split(","); String serverName = contents[0]; String tableName = contents[1]; long tableCount = server.getTableCount(serverName, tableName); String newMessage = String.format("%s,%s,%d", serverName, tableName, tableCount); MiddlewarePacket sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_TABLE_COUNT, newMessage); ctx.writeAndFlush(sendPacket); Log.debug("table count sent for " + tableName); } else if (header == MiddlewareConstants.PACKET_REQUEST_QUERY_STATISTICS) { String body = packet.body; String[] contents = body.split(",", 4); String serverName = contents[0]; int reqId = Integer.parseInt(contents[1]); int txType = Integer.parseInt(contents[2]); String sql = contents[3]; List<Integer> rowsAccessed = server.getNumRowAccessedByQuery(serverName, sql); String newMessage = String.format("%s,%d,%d,", serverName, txType, reqId); if (rowsAccessed != null) { for (int i = 0; i < rowsAccessed.size(); ++i) { Integer num = rowsAccessed.get(i); newMessage += num; if (i != rowsAccessed.size() - 1) { newMessage += ","; } } } MiddlewarePacket sendPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_QUERY_STATISTICS, newMessage); ctx.writeAndFlush(sendPacket); Log.debug("query statistics for " + sql); } else { Log.error("Unknown packet received: " + packet.header); } }
From source file:de.jackwhite20.comix.handler.HandshakeHandler.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception { ByteBuf copy = byteBuf.copy();//from ww w . j a va 2 s .com Protocol.readVarInt(byteBuf); int packetId = Protocol.readVarInt(byteBuf); if (packetId == 0) { if (protocolMode == ProtocolState.HANDSHAKE) { Protocol.readVarInt(byteBuf); Protocol.readString(byteBuf); byteBuf.readUnsignedShort(); protocolMode = ProtocolState.valueOf((byte) Protocol.readVarInt(byteBuf)); } if (protocolMode == ProtocolState.STATUS) { ByteBuf responseBuffer = Unpooled.buffer(); String response = Comix.getInstance().getStatusResponseString(); response = response.replace("%online%", "" + Comix.getInstance().getClientsOnline()); // Replace online count Protocol.writeVarInt(3 + response.length(), responseBuffer); // Size Protocol.writeVarInt(0, responseBuffer); // Packet id Protocol.writeString(response, responseBuffer); // Data as json string channelHandlerContext.writeAndFlush(responseBuffer); // Sending Pong instant because otherwise the pong will not receive properly! ByteBuf pongBuffer = Unpooled.buffer(); Protocol.writeVarInt(9, pongBuffer); Protocol.writeVarInt(1, pongBuffer); pongBuffer.writeLong(0); channelHandlerContext.writeAndFlush(pongBuffer); channelHandlerContext.close(); } if (protocolMode == ProtocolState.LOGIN) { if (byteBuf.readableBytes() == 0) { upstreamHandler.connectDownstream(copy); downstreamInitialized = true; out.add(copy.retain()); return; } String name = Protocol.readString(byteBuf); //TODO: Improve if (Comix.getInstance().getComixConfig().isMaintenance()) { if (Comix.getInstance().isWhitelistEnabled()) { if (!Comix.getInstance().isWhitelisted(name)) { kick(channelHandlerContext, Comix.getInstance().getWhitelistKickMessage()); } } else { kick(channelHandlerContext, Comix.getInstance().getComixConfig().getMaintenanceKickMessage()); } channelHandlerContext.close(); return; } else if (Comix.getInstance().isWhitelistEnabled() && !Comix.getInstance().isWhitelisted(name)) { kick(channelHandlerContext, Comix.getInstance().getWhitelistKickMessage()); channelHandlerContext.close(); return; } if (!downstreamInitialized) upstreamHandler.connectDownstream(copy); else upstreamHandler.addInitialPacket(copy); ComixClient comixClient = new ComixClient(name, upstreamHandler.getDownstreamHandler(), upstreamHandler); Comix.getInstance().addClient(comixClient); upstreamHandler.setClient(comixClient); channelHandlerContext.channel().pipeline().remove(this); Comix.getLogger().log(Level.INFO, "Handshake", "Player logged in: " + name); out.add(copy.retain()); } } }
From source file:de.jackwhite20.comix.handler.HandshakeHandler.java
License:Open Source License
private void kick(ChannelHandlerContext channelHandlerContext, String text) { ByteBuf test = Unpooled.buffer(); Protocol.writeVarInt(2 + text.length(), test); Protocol.writeVarInt(0, test);//from w ww . j a v a2s . com Protocol.writeString(text, test); channelHandlerContext.writeAndFlush(test); }
From source file:de.sanandrew.core.manpack.network.NetworkManager.java
License:Creative Commons License
private static void sendPacketTo(String modId, short packet, EnumPacketDirections direction, Tuple dirData, Tuple packetData) {/* w w w . j ava2 s.c om*/ try (ByteBufOutputStream bbos = new ByteBufOutputStream(Unpooled.buffer())) { bbos.writeShort(packet); IPacket pktInst = getPacketProcessor(modId).getPacketCls(packet).getConstructor().newInstance(); FMLEventChannel channel = getPacketChannel(modId); pktInst.writeData(bbos, packetData); FMLProxyPacket proxyPacket = new FMLProxyPacket(bbos.buffer(), getPacketChannelName(modId)); switch (direction) { case TO_SERVER: channel.sendToServer(proxyPacket); break; case TO_ALL: channel.sendToAll(proxyPacket); break; case TO_PLAYER: channel.sendTo(proxyPacket, (EntityPlayerMP) dirData.getValue(0)); break; case TO_ALL_IN_RANGE: channel.sendToAllAround(proxyPacket, new NetworkRegistry.TargetPoint((int) dirData.getValue(0), (double) dirData.getValue(1), (double) dirData.getValue(2), (double) dirData.getValue(3), (double) dirData.getValue(4))); break; case TO_ALL_IN_DIMENSION: channel.sendToDimension(proxyPacket, (int) dirData.getValue(0)); break; } } catch (IOException ioe) { ManPackLoadingPlugin.MOD_LOG.log(Level.ERROR, "The packet ID %d from %s cannot be processed!", packet, modId); ioe.printStackTrace(); } catch (IllegalAccessException | InstantiationException rex) { ManPackLoadingPlugin.MOD_LOG.log(Level.ERROR, "The packet ID %d from %s cannot be instantiated!", packet, modId); rex.printStackTrace(); } catch (NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } }
From source file:de.sanandrew.mods.particledeco.network.PacketProcessor.java
License:Creative Commons License
private static void sendPacketTo(short packetId, PacketDirections direction, Tuple dirData, Tuple packetData) { try (ByteBufOutputStream bbos = new ByteBufOutputStream(Unpooled.buffer())) { if (ID_TO_PACKET_MAP_.containsKey(packetId)) { bbos.writeShort(packetId);/* w w w. jav a2s .c o m*/ IPacket pktInst = ID_TO_PACKET_MAP_.get(packetId).newInstance(); pktInst.writeData(bbos, packetData); FMLProxyPacket packet = new FMLProxyPacket(bbos.buffer(), PDM_Main.MOD_CHANNEL); switch (direction) { case TO_SERVER: PDM_Main.channel.sendToServer(packet); break; case TO_ALL: PDM_Main.channel.sendToAll(packet); break; case TO_PLAYER: PDM_Main.channel.sendTo(packet, (EntityPlayerMP) dirData.getValue(0)); break; case TO_ALL_IN_RANGE: PDM_Main.channel.sendToAllAround(packet, new NetworkRegistry.TargetPoint((int) dirData.getValue(0), (double) dirData.getValue(1), (double) dirData.getValue(2), (double) dirData.getValue(3), (double) dirData.getValue(4))); break; case TO_ALL_IN_DIMENSION: PDM_Main.channel.sendToDimension(packet, (int) dirData.getValue(0)); break; } } } catch (IOException ioe) { FMLLog.log(PDM_Main.MOD_LOG, Level.ERROR, "The packet with the ID %d cannot be processed!", packetId); ioe.printStackTrace(); } catch (IllegalAccessException | InstantiationException rex) { FMLLog.log(PDM_Main.MOD_LOG, Level.ERROR, "The packet with the ID %d cannot be instantiated!", packetId); rex.printStackTrace(); } }
From source file:de.sanandrew.mods.turretmod.network.PacketSyncTileEntity.java
License:Creative Commons License
public PacketSyncTileEntity(TileClientSync tile) { this.pos = tile.getTile().getPos(); ByteBuf buf = Unpooled.buffer(); tile.toBytes(buf); this.tileBytes = buf.array(); }
From source file:deathcap.wsmc.web.HTTPHandler.java
License:Apache License
public void httpRequest(ChannelHandlerContext context, FullHttpRequest request) throws IOException { if (!request.getDecoderResult().isSuccess()) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;/*w w w . ja v a 2 s.c om*/ } if (request.getUri().equals("/server")) { context.fireChannelRead(request); return; } if ((request.getMethod() == OPTIONS || request.getMethod() == HEAD) && request.getUri().equals("/chunk")) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "POST"); if (request.getMethod() == OPTIONS) { response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept"); } sendHttpResponse(context, request, response); } if (request.getMethod() != GET) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // TODO: send browserified page if (request.getUri().equals("/")) { request.setUri("/index.html"); } InputStream stream = null; /* if (request.getUri().startsWith("/resources/")) { File file = new File( plugin.getResourceDir(), request.getUri().substring("/resources/".length()) ); stream = new FileInputStream(file); } else { */ stream = this.getClass().getClassLoader().getResourceAsStream("www" + request.getUri()); if (stream == null) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); return; } ByteBufOutputStream out = new ByteBufOutputStream(Unpooled.buffer()); copyStream(stream, out); stream.close(); out.close(); ByteBuf buffer = out.buffer(); if (request.getUri().equals("/index.html")) { String page = buffer.toString(CharsetUtil.UTF_8); page = page.replaceAll("%SERVERPORT%", Integer.toString(this.port)); buffer.release(); buffer = Unpooled.wrappedBuffer(page.getBytes(CharsetUtil.UTF_8)); } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer); if (request.getUri().startsWith("/resources/")) { response.headers().add("Access-Control-Allow-Origin", "*"); } String ext = request.getUri().substring(request.getUri().lastIndexOf('.') + 1); String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain"; if (type.startsWith("text/")) { type += "; charset=UTF-8"; } response.headers().set(CONTENT_TYPE, type); setContentLength(response, response.content().readableBytes()); sendHttpResponse(context, request, response); }