use of io.netty.channel.socket.DatagramPacket in project netty by netty.
the class NioDatagramChannel method filterOutboundMessage.
@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);
}
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 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 {
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 DatagramMulticastTest method testMulticast.
public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable {
MulticastTestHandler mhandler = new MulticastTestHandler();
sb.handler(new SimpleChannelInboundHandler<Object>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
// Nothing will be sent.
}
});
cb.handler(mhandler);
sb.option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF);
sb.option(ChannelOption.SO_REUSEADDR, true);
cb.option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF);
cb.option(ChannelOption.SO_REUSEADDR, true);
cb.localAddress(addr.getPort());
Channel sc = sb.bind().sync().channel();
if (sc instanceof OioDatagramChannel) {
// skip the test for OIO, as it fails because of
// No route to host which makes no sense.
// Maybe a JDK bug ?
sc.close().awaitUninterruptibly();
return;
}
DatagramChannel cc = (DatagramChannel) cb.bind().sync().channel();
String group = "230.0.0.1";
InetSocketAddress groupAddress = SocketUtils.socketAddress(group, addr.getPort());
cc.joinGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();
sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
assertTrue(mhandler.await());
// leave the group
cc.leaveGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();
// sleep a second to make sure we left the group
Thread.sleep(1000);
// we should not receive a message anymore as we left the group before
sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
mhandler.await();
sc.close().awaitUninterruptibly();
cc.close().awaitUninterruptibly();
}
use of io.netty.channel.socket.DatagramPacket in project netty by netty.
the class DatagramUnicastTest method testSimpleSend0.
@SuppressWarnings("deprecation")
private void testSimpleSend0(Bootstrap sb, Bootstrap cb, ByteBuf buf, boolean bindClient, final byte[] bytes, int count) throws Throwable {
final CountDownLatch latch = new CountDownLatch(count);
sb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
ByteBuf buf = msg.content();
assertEquals(bytes.length, buf.readableBytes());
for (byte b : bytes) {
assertEquals(b, buf.readByte());
}
latch.countDown();
}
});
}
});
cb.handler(new SimpleChannelInboundHandler<Object>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msgs) throws Exception {
// Nothing will be sent.
}
});
Channel sc = null;
BindException bindFailureCause = null;
for (int i = 0; i < 3; i++) {
try {
sc = sb.bind().sync().channel();
break;
} catch (Exception e) {
if (e instanceof BindException) {
logger.warn("Failed to bind to a free port; trying again", e);
bindFailureCause = (BindException) e;
refreshLocalAddress(sb);
} else {
throw e;
}
}
}
if (sc == null) {
throw bindFailureCause;
}
Channel cc;
if (bindClient) {
cc = cb.bind().sync().channel();
} else {
cb.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
cc = cb.register().sync().channel();
}
for (int i = 0; i < count; i++) {
cc.write(new DatagramPacket(buf.retain().duplicate(), addr));
}
// release as we used buf.retain() before
buf.release();
cc.flush();
assertTrue(latch.await(10, TimeUnit.SECONDS));
sc.close().sync();
cc.close().sync();
}
Aggregations