Example usage for io.netty.channel.socket DatagramPacket DatagramPacket

List of usage examples for io.netty.channel.socket DatagramPacket DatagramPacket

Introduction

In this page you can find the example usage for io.netty.channel.socket DatagramPacket DatagramPacket.

Prototype

public DatagramPacket(ByteBuf data, InetSocketAddress recipient) 

Source Link

Document

Create a new instance with the specified packet data and recipient address.

Usage

From source file:jazmin.server.relay.udp.webrtc.NettyUdpTransport.java

License:Open Source License

@Override
public void send(byte[] buf, int off, int len) throws IOException {
    System.err.println("send:" + off + "/" + len);
    if (len > getSendLimit()) {
    }/*from  www .  j a  v  a 2 s  .c  o m*/
    if (this.hasTimeout()) {
        throw new IllegalStateException("Handshake is taking too long! (>" + MAX_DELAY + "ms");
    }
    DatagramPacket dp = new DatagramPacket(Unpooled.wrappedBuffer(buf, off, len), remoteAddress);
    udpChannel.writeAndFlush(dp);
}

From source file:me.melchor9000.net.UDPSocket.java

License:Open Source License

public Future<Void> sendAsyncTo(ByteBuf data, final int bytes, InetSocketAddress endpoint) {
    checkSocketCreated("sendAsyncTo");
    final ByteBuf buff = channel.alloc().directBuffer(bytes).retain();
    buff.writeBytes(data, bytes);//w  ww.j  av  a 2 s .c o  m
    return createFuture(
            channel.writeAndFlush(new DatagramPacket(buff, endpoint)).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    buff.release();
                }
            }));
}

From source file:net.marfgamer.jraknet.client.RakNetClient.java

License:Open Source License

/**
 * Sends a raw message to the specified address. Be careful when using this
 * method, because if it is used incorrectly it could break server sessions
 * entirely! If you are wanting to send a message to a session, you are
 * probably looking for the/*from w  w  w  .  j  a  va2s  .  co  m*/
 * {@link net.marfgamer.jraknet.session.RakNetSession#sendMessage(net.marfgamer.jraknet.protocol.Reliability, net.marfgamer.jraknet.Packet)
 * sendMessage} method.
 * 
 * @param buf
 *            the buffer to send.
 * @param address
 *            the address to send the buffer to.
 */
public final void sendNettyMessage(ByteBuf buf, InetSocketAddress address) {
    channel.writeAndFlush(new DatagramPacket(buf, address));
    RakNetLogger.debug(this, "Sent netty message with size of " + buf.capacity() + " bytes ("
            + (buf.capacity() * 8) + " bits) to " + address);
}

From source file:net.marfgamer.jraknet.server.RakNetServer.java

License:Open Source License

/**
 * Sends a raw message to the specified address. Be careful when using this
 * method, because if it is used incorrectly it could break server sessions
 * entirely! If you are wanting to send a message to a session, you are
 * probably looking for the/*from w  w w . j av a 2s  . co m*/
 * {@link net.marfgamer.jraknet.session.RakNetSession#sendMessage(net.marfgamer.jraknet.protocol.Reliability, net.marfgamer.jraknet.Packet)
 * sendMessage} method.
 * 
 * @param buf
 *            the buffer to send.
 * @param address
 *            the address to send the buffer to.
 */
public final void sendNettyMessage(ByteBuf buf, InetSocketAddress address) {
    channel.writeAndFlush(new DatagramPacket(buf, address));
    RakNetLogger.debug(this, "Sent netty message with size of " + buf.capacity() + " bytes ("
            + (buf.capacity() * 8) + ") to " + address);
}

From source file:net.marfgamer.jraknet.session.RakNetSession.java

License:Open Source License

/**
 * Sends a raw message./*from  w  w  w.j a  v  a2 s.  c  om*/
 * 
 * @param packet
 *            The packet to send.
 */
public final void sendRawMessage(Packet packet) {
    channel.writeAndFlush(new DatagramPacket(packet.buffer(), this.address));
    RakNetLogger.debug(loggerName,
            "Sent raw packet with size of " + packet.size() + " bytes (" + (packet.size() * 8) + " bits)");
}

From source file:net.marfgamer.jraknet.session.RakNetSession.java

License:Open Source License

/**
 * Sends a raw message//  w  w  w .  j a va2 s  . c o m
 * 
 * @param buf
 *            the buffer to send.
 */
public final void sendRawMessage(ByteBuf buf) {
    channel.writeAndFlush(new DatagramPacket(buf, this.address));
    RakNetLogger.debug(loggerName,
            "Sent raw buffer with size of " + buf.capacity() + " bytes (" + (buf.capacity() * 8) + " bits)");
}

From source file:net.marfgamer.jraknet.util.RakNetUtils.java

License:Open Source License

/**
 * Sends a raw message to the specified address for the specified amount of
 * times in the specified interval until the packet is received or there is
 * a timeout./*from  w w w.  ja v a 2  s.c  om*/
 * 
 * @param address
 *            the address to send the packet to.
 * @param packet
 *            the packet to send.
 * @param timeout
 *            the interval of which the packet is sent.
 * @param retries
 *            how many times the packet will be sent.
 * @return the received packet if it was received.
 */
private static RakNetPacket createBootstrapAndSend(InetSocketAddress address, Packet packet, long timeout,
        int retries) {
    RakNetPacket packetReceived = null;

    // Create bootstrap and bind
    EventLoopGroup group = new NioEventLoopGroup();

    try {
        Bootstrap bootstrap = new Bootstrap();
        BootstrapHandler handler = new BootstrapHandler();
        bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, RakNet.MINIMUM_TRANSFER_UNIT)
                .option(ChannelOption.SO_SNDBUF, RakNet.MINIMUM_TRANSFER_UNIT).handler(handler);

        // Create channel, send packet, and close it
        Channel channel = bootstrap.bind(0).sync().channel();
        channel.writeAndFlush(new DatagramPacket(packet.buffer(), address));

        // Wait for packet to come in, return null on timeout
        while (retries > 0) {
            long sendTime = System.currentTimeMillis();
            while (System.currentTimeMillis() - sendTime < timeout) {
                if (handler.packet != null) {
                    packetReceived = handler.packet;
                    break; // We found the packet
                }
            }
            if (packetReceived != null) {
                break; // the master loop is no longer needed
            }
            retries--;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Shutdown bootstrap
    group.shutdownGracefully();
    return packetReceived;
}

From source file:netty.protocol.udp.ChineseProverbServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    String req = msg.content().toString(CharsetUtil.UTF_8);
    System.out.println(req);/*w  w  w .j a v a  2  s.  c o m*/
    if ("?".equals(req)) {
        ctx.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer(": " + nextQuote(), CharsetUtil.UTF_8), msg.sender()));
    }
}

From source file:nz.co.fortytwo.signalk.server.CamelUdpNettyHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    String request = packet.content().toString(CharsetUtil.UTF_8);
    if (logger.isDebugEnabled())
        logger.debug("Sender " + packet.sender() + " sent request:" + request);

    if (!sessionList.inverse().containsKey(packet.sender())) {
        String session = UUID.randomUUID().toString();
        String localAddress = ctx.channel().localAddress().toString();
        String remoteAddress = ctx.channel().remoteAddress().toString();
        SubscriptionManagerFactory.getInstance().add(session, session, outputType, localAddress, remoteAddress);
        sessionList.put(session, packet.sender());
        if (logger.isDebugEnabled())
            logger.debug("Added Sender " + packet.sender() + ", session:" + session);
        ctx.channel()//from   ww w  .  j a  v a2 s . c  om
                .writeAndFlush(new DatagramPacket(
                        Unpooled.copiedBuffer(Util.getWelcomeMsg().toString() + "\r\n", CharsetUtil.UTF_8),
                        packet.sender()));
    }

    Map<String, Object> headers = getHeaders(sessionList.inverse().get(packet.sender()));
    producer.sendBodyAndHeaders(request, headers);
}

From source file:nz.co.fortytwo.signalk.server.NettyServer.java

License:Open Source License

@Override
public void process(Exchange exchange) throws Exception {
    logger.debug("Received msg : " + exchange.getIn().getBody());
    String msg = exchange.getIn().getBody().toString();
    if (msg != null) {
        //get the session
        String session = exchange.getIn().getHeader(WebsocketConstants.CONNECTION_KEY, String.class);

        if (WebsocketConstants.SEND_TO_ALL.equals(session)) {
            //udp
            if (udpPort > 0 && udpChannel != null && udpChannel.isWritable()) {
                for (InetSocketAddress client : udpHandler.getSessionList().values()) {
                    if (logger.isDebugEnabled())
                        logger.debug("Sending udp: " + exchange.getIn().getBody());
                    //udpCtx.pipeline().writeAndFlush(msg+"\r\n");
                    udpChannel.writeAndFlush(
                            new DatagramPacket(Unpooled.copiedBuffer(msg + "\r\n", CharsetUtil.UTF_8), client));
                    if (logger.isDebugEnabled())
                        logger.debug("Sent udp to " + client);
                }// w w w . ja v  a2  s. co m
            }
            //tcp
            for (String key : forwardingHandler.getContextList().keySet()) {
                ChannelHandlerContext ctx = forwardingHandler.getChannel(key);
                if (ctx != null && ctx.channel().isWritable())
                    ctx.pipeline().writeAndFlush(msg + "\r\n");
            }
        } else {
            //udp
            if (udpPort > 0 && udpChannel != null && udpChannel.isWritable()) {
                final InetSocketAddress client = udpHandler.getSessionList().get(session);
                if (logger.isDebugEnabled())
                    logger.debug("Sending udp: " + exchange.getIn().getBody());
                //udpCtx.pipeline().writeAndFlush(msg+"\r\n");
                udpChannel.writeAndFlush(
                        new DatagramPacket(Unpooled.copiedBuffer(msg + "\r\n", CharsetUtil.UTF_8), client));
                if (logger.isDebugEnabled())
                    logger.debug("Sent udp for session: " + session);
                //TODO: how do we tell when a UDP client is gone
            }
            //tcp
            ChannelHandlerContext ctx = forwardingHandler.getChannel(session);
            if (ctx != null && ctx.channel().isWritable())
                ctx.pipeline().writeAndFlush(msg + "\r\n");
        }
    }

}