use of io.netty.channel.socket.DatagramPacket in project netty by netty.
the class OioDatagramChannel method doReadMessages.
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
DatagramChannelConfig config = config();
final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
ByteBuf data = config.getAllocator().heapBuffer(allocHandle.guess());
boolean free = true;
try {
// Ensure we null out the address which may have been set before.
tmpPacket.setAddress(null);
tmpPacket.setData(data.array(), data.arrayOffset(), data.capacity());
socket.receive(tmpPacket);
InetSocketAddress remoteAddr = (InetSocketAddress) tmpPacket.getSocketAddress();
allocHandle.lastBytesRead(tmpPacket.getLength());
buf.add(new DatagramPacket(data.writerIndex(allocHandle.lastBytesRead()), localAddress(), remoteAddr));
free = false;
return 1;
} catch (SocketTimeoutException e) {
// Expected
return 0;
} catch (SocketException e) {
if (!e.getMessage().toLowerCase(Locale.US).contains("socket closed")) {
throw e;
}
return -1;
} catch (Throwable cause) {
PlatformDependent.throwException(cause);
return -1;
} finally {
if (free) {
data.release();
}
}
}
use of io.netty.channel.socket.DatagramPacket in project netty by netty.
the class NioDatagramChannel method doReadMessages.
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
DatagramChannel ch = javaChannel();
DatagramChannelConfig config = config();
RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
ByteBuf data = allocHandle.allocate(config.getAllocator());
allocHandle.attemptedBytesRead(data.writableBytes());
boolean free = true;
try {
ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes());
int pos = nioData.position();
InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData);
if (remoteAddress == null) {
return 0;
}
allocHandle.lastBytesRead(nioData.position() - pos);
buf.add(new DatagramPacket(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()), localAddress(), remoteAddress));
free = false;
return 1;
} catch (Throwable cause) {
PlatformDependent.throwException(cause);
return -1;
} finally {
if (free) {
data.release();
}
}
}
use of io.netty.channel.socket.DatagramPacket in project netty by netty.
the class PcapWriteHandlerTest method udpV4.
@Test
public void udpV4() throws InterruptedException {
ByteBuf byteBuf = Unpooled.buffer();
InetSocketAddress srvReqAddr = new InetSocketAddress("127.0.0.1", 0);
InetSocketAddress cltReqAddr = new InetSocketAddress("127.0.0.1", 0);
NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(2);
// We'll bootstrap a UDP Server to avoid "Network Unreachable errors" when sending UDP Packet.
Bootstrap server = new Bootstrap().group(eventLoopGroup).channel(NioDatagramChannel.class).handler(new SimpleChannelInboundHandler<DatagramPacket>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
// Discard
}
});
ChannelFuture channelFutureServer = server.bind(srvReqAddr).sync();
assertTrue(channelFutureServer.isSuccess());
// We'll bootstrap a UDP Client for sending UDP Packets to UDP Server.
Bootstrap client = new Bootstrap().group(eventLoopGroup).channel(NioDatagramChannel.class).handler(new PcapWriteHandler(new ByteBufOutputStream(byteBuf)));
ChannelFuture channelFutureClient = client.connect(channelFutureServer.channel().localAddress(), cltReqAddr).sync();
assertTrue(channelFutureClient.isSuccess());
Channel clientChannel = channelFutureClient.channel();
assertTrue(clientChannel.writeAndFlush(Unpooled.wrappedBuffer("Meow".getBytes())).sync().isSuccess());
assertTrue(eventLoopGroup.shutdownGracefully().sync().isSuccess());
// Verify Pcap Global Headers
verifyGlobalHeaders(byteBuf);
// Verify Pcap Packet Header
// Just read, we don't care about timestamps for now
byteBuf.readInt();
// Just read, we don't care about timestamps for now
byteBuf.readInt();
// Length of Packet Saved In Pcap
assertEquals(46, byteBuf.readInt());
// Actual Length of Packet
assertEquals(46, byteBuf.readInt());
// -------------------------------------------- Verify Packet --------------------------------------------
// Verify Ethernet Packet
ByteBuf ethernetPacket = byteBuf.readBytes(46);
ByteBuf dstMac = ethernetPacket.readBytes(6);
ByteBuf srcMac = ethernetPacket.readBytes(6);
assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, -1 }, ByteBufUtil.getBytes(dstMac));
assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, 0 }, ByteBufUtil.getBytes(srcMac));
assertEquals(0x0800, ethernetPacket.readShort());
// Verify IPv4 Packet
ByteBuf ipv4Packet = ethernetPacket.readBytes(32);
// Version + IHL
assertEquals(0x45, ipv4Packet.readByte());
// DSCP
assertEquals(0x00, ipv4Packet.readByte());
// Length
assertEquals(32, ipv4Packet.readShort());
// Identification
assertEquals(0x0000, ipv4Packet.readShort());
// Fragment
assertEquals(0x0000, ipv4Packet.readShort());
// TTL
assertEquals((byte) 0xff, ipv4Packet.readByte());
// Protocol
assertEquals((byte) 17, ipv4Packet.readByte());
// Checksum
assertEquals(0, ipv4Packet.readShort());
InetSocketAddress localAddr = (InetSocketAddress) clientChannel.remoteAddress();
// Source IPv4 Address
assertEquals(NetUtil.ipv4AddressToInt((Inet4Address) localAddr.getAddress()), ipv4Packet.readInt());
InetSocketAddress remoteAddr = (InetSocketAddress) clientChannel.localAddress();
// Destination IPv4 Address
assertEquals(NetUtil.ipv4AddressToInt((Inet4Address) remoteAddr.getAddress()), ipv4Packet.readInt());
// Verify UDP Packet
ByteBuf udpPacket = ipv4Packet.readBytes(12);
// Source Port
assertEquals(remoteAddr.getPort() & 0xffff, udpPacket.readUnsignedShort());
// Destination Port
assertEquals(localAddr.getPort() & 0xffff, udpPacket.readUnsignedShort());
// Length
assertEquals(12, udpPacket.readShort());
// Checksum
assertEquals(0x0001, udpPacket.readShort());
// Verify Payload
ByteBuf payload = udpPacket.readBytes(4);
// Payload
assertArrayEquals("Meow".getBytes(CharsetUtil.UTF_8), ByteBufUtil.getBytes(payload));
// Release all ByteBuf
assertTrue(dstMac.release());
assertTrue(srcMac.release());
assertTrue(payload.release());
assertTrue(byteBuf.release());
assertTrue(ethernetPacket.release());
assertTrue(ipv4Packet.release());
assertTrue(udpPacket.release());
}
use of io.netty.channel.socket.DatagramPacket in project Glowstone by GlowstoneMC.
the class QueryTest method testChannelRead.
private void testChannelRead(QueryHandler handler, byte[] recv, byte[] send) throws Exception {
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
ByteBufAllocator alloc = mock(ByteBufAllocator.class);
when(ctx.alloc()).thenReturn(alloc);
when(alloc.buffer()).thenReturn(Unpooled.buffer());
DatagramPacket packet = new DatagramPacket(Unpooled.wrappedBuffer(recv), null, address);
handler.channelRead(ctx, packet);
verify(ctx).write(argThat(new DatagramPacketMatcher(send)));
}
use of io.netty.channel.socket.DatagramPacket in project ribbon by Netflix.
the class UdpClientTest method testUdpClientTimeout.
@Test
public void testUdpClientTimeout() throws Exception {
int port = choosePort();
UdpServer<DatagramPacket, DatagramPacket> server = new HelloUdpServer(port, 5000).createServer();
server.start();
BaseLoadBalancer lb = new BaseLoadBalancer();
Server myServer = new Server("localhost", port);
lb.setServersList(Lists.newArrayList(myServer));
MyUDPClient client = new MyUDPClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues());
try {
String response = client.submit("Is there anybody out there?").map(new Func1<DatagramPacket, String>() {
@Override
public String call(DatagramPacket datagramPacket) {
return datagramPacket.content().toString(Charset.defaultCharset());
}
}).toBlocking().first();
fail("Exception expected");
} catch (Exception e) {
assertTrue(e.getCause() instanceof TimeoutException);
assertEquals(1, client.getLoadBalancerContext().getServerStats(myServer).getSuccessiveConnectionFailureCount());
} finally {
server.shutdown();
}
}
Aggregations