io.netty.channel.socket.DatagramPacket Java Examples
The following examples show how to use
io.netty.channel.socket.DatagramPacket.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KcpTestClient.java From dfactor with MIT License | 6 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket pack) throws Exception { final ByteBuf buf = pack.content(); final int size = buf.readableBytes(); if(size > 0){ int connId = 0; if(buf.readByte()==Kcp.FLAG && size > 1 + 4){ //valid kcp head connId = buf.getInt(buf.readerIndex()); } if(connId > 0){ //valid kcp pack pack.retain(); queueRecv.offer(pack); // log.I("Recv kcp pack, sender="+pack.sender().toString()); }else{ //normal udp pack log.I("Recv udp pack, sender="+pack.sender().toString()); } }else{ log.E("Invalid pack, len=0, sender="+pack.sender().toString()); } }
Example #2
Source File: IrisUpnpServer.java From arcusplatform with Apache License 2.0 | 6 votes |
private void handleUpnpMsearchResponse(DatagramPacket packet, HttpResponse response) { HttpHeaders headers = response.headers(); if (!parseUsnHeader(headers)) { log.trace("dropping upnp m-search response with bad usn"); return; } String url = headers.get("LOCATION"); long maxAge = parseCacheControlHeader(headers); if (log.isTraceEnabled()) { log.trace("upnp msearch response: cache={}s, sender={}, uuid={}, class={}, namespace={}, type={}, version={}\n{}", TimeUnit.SECONDS.convert(maxAge,TimeUnit.NANOSECONDS), packet.sender(), usn.deviceUuid, usn.clazz, usn.namespace, usn.type, usn.version, response); } IrisUpnpService.poke(packet.sender(), usn, maxAge, url, headers); }
Example #3
Source File: UdpServerChannel.java From UdpServerSocketChannel with GNU Lesser General Public License v3.0 | 6 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket p) throws Exception { UdpChannel channel = userChannels.compute(p.sender(), (lAddr, lChannel) -> { return ((lChannel == null) || !lChannel.isOpen()) ? new UdpChannel(UdpServerChannel.this, lAddr) : lChannel; }); channel.buffers.add(p.content().retain()); if (channel.getIsNew()) { ChannelPipeline serverPipeline = UdpServerChannel.this.pipeline(); serverPipeline.fireChannelRead(channel); serverPipeline.fireChannelReadComplete(); } else { if (channel.isRegistered()) { channel.read(); } } }
Example #4
Source File: IrisUpnpServer.java From arcusplatform with Apache License 2.0 | 6 votes |
private void handleResponse(@Nullable ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { EmbeddedChannel http = new EmbeddedChannel(new HttpResponseDecoder()); try { http.writeInbound(Unpooled.unreleasableBuffer(packet.content())); http.finish(); while (true) { Object result = http.readInbound(); if (result == null) { break; } if (result instanceof HttpResponse) { HttpResponse res = (HttpResponse)result; switch (res.getStatus().code()) { case 200: handleUpnpMsearchResponse(packet, res); break; default: log.debug("unknown upnp response: {}", res.getStatus().code()); break; } } } } finally { http.finishAndReleaseAll(); } }
Example #5
Source File: UDPMessageDeserializer.java From datacollector with Apache License 2.0 | 6 votes |
public UDPMessage deserialize(byte[] buffer) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(buffer); ObjectInputStream ois = new ObjectInputStream(bais); int version = ois.readInt(); if (version == UDPConstants.UDP_MESSAGE_VERSION) { int type = ois.readInt(); long received = ois.readLong(); String address = ois.readUTF(); int port = ois.readInt(); InetSocketAddress sender = new InetSocketAddress(address, port); address = ois.readUTF(); port = ois.readInt(); InetSocketAddress receiver = new InetSocketAddress(address, port); int dataLen = ois.readInt(); byte[] data = new byte[dataLen]; ois.readFully(data); ois.close(); ByteBuf byteBuf = Unpooled.wrappedBuffer(data); DatagramPacket datagram = new DatagramPacket(byteBuf, receiver, sender); return new UDPMessage(type, received, datagram); } else { throw new IOException(Utils.format("Unsupported version '{}'", version)); } }
Example #6
Source File: DatagramDnsResponseDecoder.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
private static DnsResponse newResponse(DatagramPacket packet, ByteBuf buf) { final int id = buf.readUnsignedShort(); final int flags = buf.readUnsignedShort(); if (flags >> 15 == 0) { throw new CorruptedFrameException("not a response"); } final DnsResponse response = new DatagramDnsResponse( packet.sender(), packet.recipient(), id, DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)), DnsResponseCode.valueOf((byte) (flags & 0xf))); response.setRecursionDesired((flags >> 8 & 1) == 1); response.setAuthoritativeAnswer((flags >> 10 & 1) == 1); response.setTruncated((flags >> 9 & 1) == 1); response.setRecursionAvailable((flags >> 7 & 1) == 1); response.setZ(flags >> 4 & 0x7); return response; }
Example #7
Source File: DatagramDnsQueryEncoder.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Override protected void encode( ChannelHandlerContext ctx, AddressedEnvelope<DnsQuery, InetSocketAddress> in, List<Object> out) throws Exception { final InetSocketAddress recipient = in.recipient(); final DnsQuery query = in.content(); final ByteBuf buf = allocateBuffer(ctx, in); boolean success = false; try { encodeHeader(query, buf); encodeQuestions(query, buf); encodeRecords(query, DnsSection.ADDITIONAL, buf); success = true; } finally { if (!success) { buf.release(); } } out.add(new DatagramPacket(buf, recipient, null)); }
Example #8
Source File: PacketDecoder.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception { ByteBuf buf = packet.content(); int length = buf.readableBytes(); if (length <= 1 || length >= MAXSIZE) { logger .error("UDP rcv bad packet, from {} length = {}", ctx.channel().remoteAddress(), length); return; } byte[] encoded = new byte[length]; buf.readBytes(encoded); try { UdpEvent event = new UdpEvent(Message.parse(encoded), packet.sender()); out.add(event); } catch (Exception e) { logger.error("Parse msg failed, type {}, len {}, address {}", encoded[0], encoded.length, packet.sender()); } }
Example #9
Source File: DHTServerHandler.java From Dodder with MIT License | 6 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { byte[] buff = new byte[packet.content().readableBytes()]; packet.content().readBytes(buff); pool.execute(() -> { Map<String, ?> map = BencodingUtils.decode(buff); if (map == null || map.get("y") == null) return; String y = new String((byte[]) map.get("y")); if ("q".equals(y)) { //请求 Queries onQuery(map, packet.sender()); } else if ("r".equals(y)) { //回复 Responses onResponse(map, packet.sender()); } }); }
Example #10
Source File: GelfMessageUdpEncoderTest.java From gelfclient with Apache License 2.0 | 6 votes |
@Test public void testEncode() throws Exception { InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 12201); EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageUdpEncoder(remoteAddress)); // Test writing. assertTrue(channel.writeOutbound(Unpooled.wrappedBuffer("test".getBytes(StandardCharsets.US_ASCII)))); assertTrue(channel.finish()); // Test reading. DatagramPacket datagramPacket = (DatagramPacket) channel.readOutbound(); byte[] bytes = new byte[datagramPacket.content().readableBytes()]; datagramPacket.content().getBytes(0, bytes); assertEquals(remoteAddress, datagramPacket.recipient()); assertEquals("test", new String(bytes, StandardCharsets.US_ASCII)); }
Example #11
Source File: HelloUdpServer.java From ribbon with Apache License 2.0 | 6 votes |
public UdpServer<DatagramPacket, DatagramPacket> createServer() { UdpServer<DatagramPacket, DatagramPacket> server = RxNetty.createUdpServer(port, new ConnectionHandler<DatagramPacket, DatagramPacket>() { @Override public Observable<Void> handle(final ObservableConnection<DatagramPacket, DatagramPacket> newConnection) { return newConnection.getInput().flatMap(new Func1<DatagramPacket, Observable<Void>>() { @Override public Observable<Void> call(final DatagramPacket received) { return Observable.interval(delay, TimeUnit.MILLISECONDS).take(1).flatMap(new Func1<Long, Observable<Void>>() { @Override public Observable<Void> call(Long aLong) { InetSocketAddress sender = received.sender(); System.out.println("Received datagram. Sender: " + sender); ByteBuf data = newConnection.getChannel().alloc().buffer(WELCOME_MSG_BYTES.length); data.writeBytes(WELCOME_MSG_BYTES); return newConnection.writeAndFlush(new DatagramPacket(data, sender)); } }); } }); } }); System.out.println("UDP hello server started at port: " + port); return server; }
Example #12
Source File: NativeDatagramPacketArray.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
/** * Try to add the given {@link DatagramPacket}. Returns {@code true} on success, * {@code false} otherwise. */ boolean add(DatagramPacket packet) { if (count == packets.length) { return false; } ByteBuf content = packet.content(); int len = content.readableBytes(); if (len == 0) { return true; } NativeDatagramPacket p = packets[count]; InetSocketAddress recipient = packet.recipient(); if (!p.init(content, recipient)) { return false; } count++; return true; }
Example #13
Source File: MasterServerPacketDecoder.java From async-gamequery-lib with MIT License | 6 votes |
@Override protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception { //Create our response packet from the datagram we received final MasterServerResponsePacket packet = builder.construct(msg.content()); if (packet != null) { final MasterServerResponse response = new MasterServerResponse(); if (response != null) { response.setSender(msg.sender()); response.setRecipient(msg.recipient()); response.setResponsePacket(packet); log.debug("Receiving Data '{}' from '{}' using Channel Id: {}", response.getClass().getSimpleName(), ctx.channel().remoteAddress(), ctx.channel().id()); //Pass the message back to the messenger responseCallback.accept(response, null); return; } } throw new IllegalStateException("No response packet found for the incoming datagram"); }
Example #14
Source File: HeartBeatHandler.java From netty-cookbook with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { System.err.println(packet); String s = packet.content().toString(CharsetUtil.UTF_8); System.out.println(s); ByteBuf buf = Unpooled.copiedBuffer("I'm alive at "+new Date(), CharsetUtil.UTF_8); ctx.write(new DatagramPacket(buf, packet.sender())); }
Example #15
Source File: QuoteOfTheMomentClientHandler.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override public void channelRead0(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(); } }
Example #16
Source File: Fragment.java From plog with Apache License 2.0 | 5 votes |
public static Fragment fromDatagram(DatagramPacket packet) { final ByteBuf content = packet.content().order(ByteOrder.BIG_ENDIAN); final int length = content.readableBytes(); if (length < HEADER_SIZE) { throw new IllegalArgumentException("Packet too short: " + length + " bytes"); } final int fragmentCount = content.getUnsignedShort(2); if (fragmentCount == 0) { throw new IllegalArgumentException("0 fragment count"); } final int fragmentIndex = content.getUnsignedShort(4); if (fragmentIndex >= fragmentCount) { throw new IllegalArgumentException("Index " + fragmentIndex + " < count " + fragmentCount); } final int fragmentSize = content.getUnsignedShort(6); final int idRightPart = content.getInt(8); final int totalLength = content.getInt(12); if (totalLength < 0) { throw new IllegalArgumentException("Cannot support length " + totalLength + " > 2^31"); } final int msgHash = content.getInt(16); final int tagsBufferLength = content.getUnsignedShort(20); final ByteBuf tagsBuffer = tagsBufferLength == 0 ? null : content.slice(HEADER_SIZE, tagsBufferLength); final int payloadLength = length - HEADER_SIZE - tagsBufferLength; final ByteBuf payload = content.slice(HEADER_SIZE + tagsBufferLength, payloadLength); final int port = packet.sender().getPort(); final long msgId = (((long) port) << Integer.SIZE) + idRightPart; return new Fragment(fragmentCount, fragmentIndex, fragmentSize, msgId, totalLength, msgHash, payload, tagsBuffer); }
Example #17
Source File: IrisUpnpServer.java From arcusplatform with Apache License 2.0 | 5 votes |
private ChannelFuture respondDevice(InetSocketAddress to, Channel ch, String date) { ByteBuf data = Unpooled.buffer(); ByteBufUtil.writeUtf8(data, "HTTP/1.1 200 OK\r\n" + "CACHE-CONTROL: max-age=1800\r\n" + "DATE: " + date + "\r\n" + "EXT:\r\n" + "LOCATION: http://" + addr + ":" + HttpServer.PORT + "/upnp/device.xml\r\n" + "ST: uuid:" + IrisUpnpService.uuid + "\r\n" + "USN: uuid:" + IrisUpnpService.uuid + "\r\n" + "SERVER: Iris OS/2.0 UPnP/1.0 Iris/2.0\r\n\r\n" ); return ch.writeAndFlush(new DatagramPacket(data,to)); }
Example #18
Source File: PacketQueueUDPHandler.java From datacollector with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { packet.retain(); final boolean succeeded = queue.offer(packet); if (succeeded) { gaugeMap.put(GAUGE_NUM_QUEUED_PACKETS, queuedPacketCount.incrementAndGet()); gaugeMap.put(GAUGE_PACKET_QUEUE_SIZE, queue.size()); } else { gaugeMap.put(GAUGE_NUM_DROPPED_PACKETS, droppedPacketCount.incrementAndGet()); // allow Netty to collect the buffer packet.release(); } }
Example #19
Source File: ModbusServer4MasterApp.java From easymodbus4j with GNU Lesser General Public License v3.0 | 5 votes |
public static void start(ModbusConfig cfg) throws Exception { ModbusConstants.MASTER_SHOW_DEBUG_LOG = cfg.showDebugLog; ModbusConstants.DEFAULT_UNIT_IDENTIFIER = cfg.unit_IDENTIFIER; DeviceCommandPluginRegister.getInstance().reg(DeviceCommandV1PluginImpl.class.newInstance()); DeviceRepositoryPluginRegister.getInstance().reg(DeviceRepositoryV1PluginImpl.class.newInstance()); ModbusSetup setup = new ModbusSetup(); setup.setHandler(null, new CustomModbusMasterResponseHandler(cfg.transactionIdentifierOffset)); setup.setupServer4Master(cfg.port); Collection<Channel> channels = setup.getModbusServer().getChannels(); UdpServer udpServer = new UdpServer(); SimpleChannelInboundHandler<DatagramPacket> handler = new UdpServerHandler4SendToServer(channels); udpServer.setup(cfg.udpPort, handler); int sleep = cfg.sleep; if (cfg.autoSend) { Thread.sleep(sleep); ModbusMasterSchedule4DeviceId modbusMasterSchedule4DeviceId = new ModbusMasterSchedule4DeviceId(); modbusMasterSchedule4DeviceId.run(channels); modbusMasterSchedule4DeviceId.schedule(channels, sleep * 5); ModbusMasterSchedule4All modbusMasterSchedule4All = new ModbusMasterSchedule4All(); modbusMasterSchedule4All.schedule(channels, sleep); } Runnable runnable = () -> ConsoleUtil.clearConsole(true); ScheduledUtil.scheduleWithFixedDelay(runnable, sleep * 5); }
Example #20
Source File: DatagramPacketDecoderTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testDecode() { InetSocketAddress recipient = SocketUtils.socketAddress("127.0.0.1", 10000); InetSocketAddress sender = SocketUtils.socketAddress("127.0.0.1", 20000); ByteBuf content = Unpooled.wrappedBuffer("netty".getBytes(CharsetUtil.UTF_8)); assertTrue(channel.writeInbound(new DatagramPacket(content, recipient, sender))); assertEquals("netty", channel.readInbound()); }
Example #21
Source File: UDPTestUtil.java From datacollector with Apache License 2.0 | 5 votes |
public static byte[] getUDPData(int type, byte[] data) throws IOException { InetSocketAddress recipient = new InetSocketAddress("127.0.0.1", 2000); InetSocketAddress sender = new InetSocketAddress("127.0.0.1", 3000); ByteBuf buffer = Unpooled.wrappedBuffer(data); DatagramPacket datagram = new DatagramPacket(buffer, recipient, sender); UDPMessage message = new UDPMessage(type, 1, datagram); UDPMessageSerializer serializer = new UDPMessageSerializer(); return serializer.serialize(message); }
Example #22
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #23
Source File: WireTrafficStats.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { outPackets.incrementAndGet(); if (msg instanceof ByteBuf) { outSize.addAndGet(((ByteBuf) msg).readableBytes()); } else if (msg instanceof DatagramPacket) { outSize.addAndGet(((DatagramPacket) msg).content().readableBytes()); } super.write(ctx, msg, promise); }
Example #24
Source File: QuoteOfTheMomentServerHandler.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { System.err.println(packet); if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) { ctx.write(new DatagramPacket( Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } }
Example #25
Source File: TestClient.java From riiablo with Apache License 2.0 | 5 votes |
@Override public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap() .group(group) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) { UnicastEndpoint<DatagramPacket> endpoint = new ReliableEndpoint(ch, TestClient.this); TestClient.this.endpoint = endpoint; ch.pipeline() .addLast(new EndpointedChannelHandler<>(DatagramPacket.class, endpoint)) ; } }); ChannelFuture f = b.connect("localhost", TestServer.PORT).sync(); sendPacket(); } catch (Throwable t) { Gdx.app.error(TAG, t.getMessage(), t); Gdx.app.exit(); } }
Example #26
Source File: DatagramPacketDecoder.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override public boolean acceptInboundMessage(Object msg) throws Exception { if (msg instanceof DatagramPacket) { return decoder.acceptInboundMessage(((DatagramPacket) msg).content()); } return false; }
Example #27
Source File: CopyByteBufHandlerTest.java From servicetalk with Apache License 2.0 | 5 votes |
@Test public void doesNotProcessByteBufHolder() { CopyByteBufHandler handler = new CopyByteBufHandler(UnpooledByteBufAllocator.DEFAULT); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); ByteBuf buf = mock(ByteBuf.class); IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, // Use DatagramPacket as a ByteBufHolder implementation: () -> handler.channelRead(ctx, new DatagramPacket(buf, mock(InetSocketAddress.class)))); assertThat(ex.getMessage(), startsWith("Unexpected ReferenceCounted msg")); verify(ctx, never()).fireChannelRead(any()); verify(buf).release(); }
Example #28
Source File: DnsResponseTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void readMalformedResponseTest() throws Exception { EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder()); ByteBuf packet = embedder.alloc().buffer(512).writeBytes(malformedLoopPacket); exception.expect(CorruptedFrameException.class); embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0))); }
Example #29
Source File: LispMessageDecoder.java From onos with Apache License 2.0 | 5 votes |
@Override protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> list) throws Exception { ByteBuf byteBuf = msg.content(); LispMessageReader reader = LispMessageReaderFactory.getReader(byteBuf); LispMessage message = (LispMessage) reader.readFrom(byteBuf); message.configSender(msg.sender()); list.add(message); }
Example #30
Source File: ClientHandler.java From chuidiang-ejemplos with GNU Lesser General Public License v3.0 | 5 votes |
public void sendMessage(String message){ if (null==ctx) return; ByteBuf buff = ctx.alloc().buffer(); buff.writeCharSequence(message,Charset.defaultCharset()); DatagramPacket packet = new DatagramPacket(buff, new InetSocketAddress("239.255.27.1",1234)); ctx.writeAndFlush(packet); }