List of usage examples for io.netty.buffer Unpooled buffer
public static ByteBuf buffer(int initialCapacity)
From source file:de.gandev.modjn.entity.func.response.ReadDiscreteInputsResponse.java
License:Apache License
@Override public ByteBuf encode() { ByteBuf buf = Unpooled.buffer(calculateLength()); buf.writeByte(getFunctionCode());/*from w w w.j a v a 2 s . c o m*/ buf.writeByte(byteCount); buf.writeBytes(inputStatus.toByteArray()); return buf; }
From source file:de.gandev.modjn.entity.func.response.ReadHoldingRegistersResponse.java
License:Apache License
@Override public ByteBuf encode() { ByteBuf buf = Unpooled.buffer(calculateLength()); buf.writeByte(getFunctionCode());//from w w w . j a v a 2 s . c o m buf.writeByte(byteCount); for (int i = 0; i < registers.length; i++) { buf.writeShort(registers[i]); } return buf; }
From source file:de.gandev.modjn.entity.func.response.ReadInputRegistersResponse.java
License:Apache License
@Override public ByteBuf encode() { ByteBuf buf = Unpooled.buffer(calculateLength()); buf.writeByte(getFunctionCode());// ww w . j a va 2s. c o m buf.writeByte(byteCount); for (int i = 0; i < inputRegisters.length; i++) { buf.writeShort(inputRegisters[i]); } return buf; }
From source file:discord4j.voice.VoiceSocket.java
License:Open Source License
Mono<InetSocketAddress> performIpDiscovery(int ssrc) { Mono<Void> sendDiscoveryPacket = Mono.fromRunnable(() -> { ByteBuf discoveryPacket = Unpooled.buffer(DISCOVERY_PACKET_LENGTH).writeInt(ssrc) .writeZero(DISCOVERY_PACKET_LENGTH - Integer.BYTES); outbound.onNext(discoveryPacket); });//w ww . j av a 2 s. c om Mono<InetSocketAddress> parseResponse = inbound.next().map(buf -> { String address = getNullTerminatedString(buf, Integer.BYTES); // undocumented: discord replies with the ssrc first, THEN the IP address int port = buf.getUnsignedShortLE(DISCOVERY_PACKET_LENGTH - Short.BYTES); buf.release(); return InetSocketAddress.createUnresolved(address, port); }); return sendDiscoveryPacket.then(parseResponse); }
From source file:dorkbox.network.Broadcast.java
License:Apache License
static List<BroadcastResponse> discoverHosts0(Logger logger, int udpPort, int discoverTimeoutMillis, boolean fetchAllServers) throws IOException { // fetch a buffer that contains the serialized object. ByteBuf buffer = Unpooled.buffer(1); buffer.writeByte(MagicBytes.broadcastID); List<BroadcastResponse> servers = new ArrayList<BroadcastResponse>(); Enumeration<NetworkInterface> networkInterfaces; try {//from w w w . ja v a2 s . c om networkInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { if (logger != null) { logger.error("Host discovery failed.", e); } throw new IOException("Host discovery failed. No interfaces found."); } scan: for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) { for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress address = interfaceAddress.getAddress(); InetAddress broadcast = interfaceAddress.getBroadcast(); // don't use IPv6! if (address instanceof Inet6Address) { if (logger != null) { if (logger.isInfoEnabled()) { logger.info("Not using IPv6 address: {}", address); } } continue; } try { if (logger != null) { if (logger.isInfoEnabled()) { logger.info("Searching for host on [{}:{}]", address.getHostAddress(), udpPort); } } EventLoopGroup group; Class<? extends Channel> channelClass; if (OS.isAndroid()) { // android ONLY supports OIO (not NIO) group = new OioEventLoopGroup(1); channelClass = OioDatagramChannel.class; } else { group = new NioEventLoopGroup(1); channelClass = NioDatagramChannel.class; } Bootstrap udpBootstrap = new Bootstrap().group(group).channel(channelClass) .option(ChannelOption.SO_BROADCAST, true).handler(new ClientDiscoverHostInitializer()) .localAddress(new InetSocketAddress(address, 0)); // pick random address. Not listen for broadcast. // we don't care about RECEIVING a broadcast packet, we are only SENDING one. ChannelFuture future; try { future = udpBootstrap.bind(); future.await(); } catch (InterruptedException e) { if (logger != null) { logger.error("Could not bind to random UDP address on the server.", e.getCause()); } throw new IOException("Could not bind to random UDP address on the server."); } if (!future.isSuccess()) { if (logger != null) { logger.error("Could not bind to random UDP address on the server.", future.cause()); } throw new IOException("Could not bind to random UDP address on the server."); } Channel channel1 = future.channel(); if (broadcast != null) { // try the "defined" broadcast first if we have it (not always!) channel1.writeAndFlush( new DatagramPacket(buffer, new InetSocketAddress(broadcast, udpPort))); // response is received. If the channel is not closed within 5 seconds, move to the next one. if (!channel1.closeFuture().awaitUninterruptibly(discoverTimeoutMillis)) { if (logger != null) { if (logger.isInfoEnabled()) { logger.info("Host discovery timed out."); } } } else { BroadcastResponse broadcastResponse = channel1.attr(ClientDiscoverHostHandler.STATE) .get(); servers.add(broadcastResponse); } // keep going if we want to fetch all servers. Break if we found one. if (!(fetchAllServers || servers.isEmpty())) { channel1.close().await(); group.shutdownGracefully().await(); break scan; } } // continue with "common" broadcast addresses. // Java 1.5 doesn't support getting the subnet mask, so try them until we find one. byte[] ip = address.getAddress(); for (int octect = 3; octect >= 0; octect--) { ip[octect] = -1; // 255.255.255.0 // don't error out on one particular octect try { InetAddress byAddress = InetAddress.getByAddress(ip); channel1.writeAndFlush( new DatagramPacket(buffer, new InetSocketAddress(byAddress, udpPort))); // response is received. If the channel is not closed within 5 seconds, move to the next one. if (!channel1.closeFuture().awaitUninterruptibly(discoverTimeoutMillis)) { if (logger != null) { if (logger.isInfoEnabled()) { logger.info("Host discovery timed out."); } } } else { BroadcastResponse broadcastResponse = channel1.attr(ClientDiscoverHostHandler.STATE) .get(); servers.add(broadcastResponse); if (!fetchAllServers) { break; } } } catch (Exception ignored) { } } channel1.close().sync(); group.shutdownGracefully(0, discoverTimeoutMillis, TimeUnit.MILLISECONDS); } catch (Exception ignored) { } // keep going if we want to fetch all servers. Break if we found one. if (!(fetchAllServers || servers.isEmpty())) { break scan; } } } if (logger != null && logger.isInfoEnabled() && !servers.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(256); if (fetchAllServers) { stringBuilder.append("Discovered servers: (").append(servers.size()).append(")"); for (BroadcastResponse server : servers) { stringBuilder.append("/n").append(server.remoteAddress).append(":"); if (server.tcpPort > 0) { stringBuilder.append(server.tcpPort); if (server.udpPort > 0) { stringBuilder.append(":"); } } if (server.udpPort > 0) { stringBuilder.append(udpPort); } } logger.info(stringBuilder.toString()); } else { BroadcastResponse server = servers.get(0); stringBuilder.append(server.remoteAddress).append(":"); if (server.tcpPort > 0) { stringBuilder.append(server.tcpPort); if (server.udpPort > 0) { stringBuilder.append(":"); } } if (server.udpPort > 0) { stringBuilder.append(udpPort); } logger.info("Discovered server [{}]", stringBuilder.toString()); } } return servers; }
From source file:dorkbox.network.serialization.Serialization.java
License:Apache License
/** * Called when initialization is complete. This is to prevent (and recognize) out-of-order class/serializer registration. If an ID * is already in use by a different type, a {@link KryoException} is thrown. *//*from ww w . j a va 2 s. co m*/ @Override public synchronized void finishInit(final Logger wireReadLogger, final Logger wireWriteLogger) { this.wireReadLogger = wireReadLogger; this.wireWriteLogger = wireWriteLogger; initialized = true; // initialize the kryo pool with at least 1 kryo instance. This ALSO makes sure that all of our class registration is done // correctly and (if not) we are are notified on the initial thread (instead of on the network update thread) KryoExtra kryo = kryoPool.take(); try { // now MERGE all of the registrations (since we can have registrations overwrite newer/specific registrations ArrayList<ClassRegistration> mergedRegistrations = new ArrayList<ClassRegistration>(); for (ClassRegistration registration : classesToRegister) { int id = registration.id; // if we ALREADY contain this registration (based ONLY on ID), then overwrite the existing one and REMOVE the current one boolean found = false; for (int index = 0; index < mergedRegistrations.size(); index++) { final ClassRegistration existingRegistration = mergedRegistrations.get(index); if (existingRegistration.id == id) { mergedRegistrations.set(index, registration); found = true; break; } } if (!found) { mergedRegistrations.add(registration); } } // now all of the registrations are IN ORDER and MERGED this.mergedRegistrations = mergedRegistrations.toArray(new ClassRegistration[0]); Object[][] registrationDetails = new Object[mergedRegistrations.size()][3]; for (int i = 0; i < mergedRegistrations.size(); i++) { final ClassRegistration registration = mergedRegistrations.get(i); registration.log(logger); // now save all of the registration IDs for quick verification/access registrationDetails[i] = new Object[] { registration.id, registration.clazz.getName(), registration.serializer.getClass().getName() }; // now we have to manage caching methods (only as necessary) if (registration.clazz.isInterface()) { // can be a normal class or an RMI class... Class<?> implClass = null; if (registration instanceof ClassSerializerRmi) { implClass = ((ClassSerializerRmi) registration).implClass; } CachedMethod[] cachedMethods = RmiUtils.getCachedMethods(Serialization.logger, kryo, useAsm, registration.clazz, implClass, registration.id); methodCache.put(registration.id, cachedMethods); } } // save this as a byte array (so registration is faster) ByteBuf buffer = Unpooled.buffer(480); kryo.setRegistrationRequired(false); try { kryo.writeCompressed(buffer, registrationDetails); } catch (Exception e) { logger.error("Unable to write compressed data for registration details"); } int length = buffer.readableBytes(); savedRegistrationDetails = new byte[length]; buffer.getBytes(0, savedRegistrationDetails, 0, length); buffer.release(); } finally { if (registrationRequired) { kryo.setRegistrationRequired(true); } kryoPool.put(kryo); } }
From source file:eu.xworlds.util.raknet.protocol.ConnectedPing.java
License:Open Source License
@Override public ByteBuf encode() { final ByteBuf result = Unpooled.buffer(1 + SIZE_TIME); result.order(ByteOrder.BIG_ENDIAN); result.writeByte(ID);// ww w. j a v a2 s . c om writeTime(result, this.time); return result; }
From source file:eu.xworlds.util.raknet.protocol.ConnectedPong.java
License:Open Source License
@Override public ByteBuf encode() { final ByteBuf result = Unpooled.buffer(1 + SIZE_TIME + SIZE_TIME); result.order(ByteOrder.BIG_ENDIAN); result.writeByte(ID);// w ww . j a v a 2s . co m writeTime(result, this.pingTime); writeTime(result, this.pongTime); return result; }
From source file:eu.xworlds.util.raknet.protocol.ConnectionRequest.java
License:Open Source License
@Override public ByteBuf encode() { int size = 1 + SIZE_GUID + SIZE_TIME + 1; if (this.doSecurity) { size += 32 + 1;/*from w ww. j a va2 s .c o m*/ if (this.doIdentity) { size += EASYHANDSHAKE_IDENTITY_BYTES; } } final ByteBuf buf = Unpooled.buffer(size); buf.order(ByteOrder.BIG_ENDIAN); buf.writeByte(ID); writeGuid(buf, this.clientGuid); writeTime(buf, this.time); buf.writeBoolean(this.doSecurity); if (this.doSecurity) { buf.writeBytes(this.proof); buf.writeBoolean(this.doIdentity); if (this.doIdentity) { buf.writeBytes(this.identity); } } return buf; }
From source file:eu.xworlds.util.raknet.protocol.DetectLostConnections.java
License:Open Source License
@Override public ByteBuf encode() { final ByteBuf buf = Unpooled.buffer(1); buf.order(ByteOrder.BIG_ENDIAN); buf.writeByte(ID); return buf; }