Example usage for java.net DatagramPacket DatagramPacket

List of usage examples for java.net DatagramPacket DatagramPacket

Introduction

In this page you can find the example usage for java.net DatagramPacket DatagramPacket.

Prototype

public DatagramPacket(byte buf[], int length, InetAddress address, int port) 

Source Link

Document

Constructs a datagram packet for sending packets of length length to the specified port number on the specified host.

Usage

From source file:org.eredlab.g4.ccl.net.tftp.TFTPRequestPacket.java

/***
 * Creates a UDP datagram containing all the TFTP
 * request packet data in the proper format.
 * This is a method exposed to the programmer in case he
 * wants to implement his own TFTP client instead of using
 * the {@link org.apache.commons.net.tftp.TFTPClient}
 * class.  Under normal circumstances, you should not have a need to call
 * this method.// www  .jav  a  2 s .  c o m
 * <p>
 * @return A UDP datagram containing the TFTP request packet.
 ***/
public final DatagramPacket newDatagram() {
    int fileLength, modeLength;
    byte[] data;

    fileLength = _filename.length();
    modeLength = _modeBytes[_mode].length;

    data = new byte[fileLength + modeLength + 4];
    data[0] = 0;
    data[1] = (byte) _type;
    System.arraycopy(_filename.getBytes(), 0, data, 2, fileLength);
    data[fileLength + 2] = 0;
    System.arraycopy(_modeBytes[_mode], 0, data, fileLength + 3, modeLength);

    return new DatagramPacket(data, data.length, _address, _port);
}

From source file:com.example.nate.cloudcar.MainActivity.java

public void socketSend(final String chan, final int pos) {
    new Thread(new Runnable() {
        public void run() {
            try {
                int msgLength = chan.length();
                DatagramSocket s = new DatagramSocket();
                InetAddress local = InetAddress.getByName("192.168.10.200");
                byte[] message = chan.getBytes();
                DatagramPacket chanPacket = new DatagramPacket(message, msgLength, local, server_port);
                s.send(chanPacket);//  w w w . j a  v  a2  s . co  m
                msgLength = Integer.toString(pos).length();
                message = Integer.toString(pos).getBytes();
                DatagramPacket posPacket = new DatagramPacket(message, msgLength, local, server_port);
                s.send(posPacket);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
    Thread.currentThread().interrupted();

}

From source file:org.opennms.netmgt.syslogd.SyslogdEventdLoadIT.java

@Test(timeout = 120000)
@Transactional//w w  w  . j  av a  2  s  .c  om
public void testRfcSyslog() throws Exception {
    loadSyslogConfiguration("/etc/syslogd-rfc-configuration.xml");

    startSyslogdGracefully();

    m_eventCounter.anticipate();

    InetAddress address = InetAddress.getLocalHost();

    // handle an invalid packet
    byte[] bytes = "<34>1 2010-08-19T22:14:15.000Z localhost - - - - BOMfoo0: load test 0 on tty1\0".getBytes();
    DatagramPacket pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT);
    new SyslogConnectionHandlerDefaultImpl().handleSyslogConnection(new SyslogConnection(pkt, m_config));

    // handle a valid packet
    bytes = "<34>1 2003-10-11T22:14:15.000Z plonk -ev/pts/8\0".getBytes();
    pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT);
    new SyslogConnectionHandlerDefaultImpl().handleSyslogConnection(new SyslogConnection(pkt, m_config));

    m_eventCounter.waitForFinish(120000);

    assertEquals(1, m_eventCounter.getCount());
}

From source file:org.openhab.binding.yeelight.internal.YeelightBinding.java

private void discoverYeelightDevices() {
    String url = null;/* w  w w .  j  a v a2  s. co  m*/

    try {
        StringBuilder sb = new StringBuilder();
        sb.append("M-SEARCH * HTTP/1.1\r\n");
        sb.append("MAN: \"ssdp:discover\"\r\n");
        sb.append("ST: wifi_bulb\r\n");

        byte[] sendData = sb.toString().getBytes("UTF-8");
        InetAddress addr = InetAddress.getByName(MCAST_ADDR);
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, addr, MCAST_PORT);

        socket.send(sendPacket);
    } catch (MalformedURLException e) {
        logger.error("The URL '{}' is malformed: ", url, e);
    } catch (Exception e) {
        logger.error("Cannot get Yeelight login cookie: ", e);
    }
}

From source file:org.lwes.emitter.DatagramSocketEventEmitter.java

/**
 * @param bytes the byte array to emit/*  w w w . j  a  v a2  s  .  c  o  m*/
 * @param address the address to use
 * @param port the port to use
 * @throws IOException throws an IOException if there is a network error
 * @return number of bytes emitted
 */
protected int emit(byte[] bytes, InetAddress address, int port) throws IOException {
    /* don't send null bytes */
    if (bytes == null)
        return 0;

    if (socket == null || socket.isClosed()) {
        throw new IOException("Socket wasn't initialized or was closed.");
    }

    DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port);
    socket.send(dp);

    if (log.isTraceEnabled()) {
        log.trace("Sent to network '" + NumberCodec.byteArrayToHexString(dp.getData(), 0, dp.getLength()));
    }
    return bytes.length;
}

From source file:org.lwes.emitter.MulticastEventEmitter.java

/**
 * Emits a byte array to the network./*from w  w  w  . j  av  a2s .  c  o m*/
 *
 * @param bytes the byte array to emit
 * @throws IOException throws an IOException if there is a network error.
 */
@Override
protected void emit(byte[] bytes) throws IOException {
    /* don't bother with empty arrays */
    if (bytes == null) {
        return;
    }
    if (socket == null || socket.isClosed()) {
        throw new IOException("Socket wasn't initialized or was closed.");
    }

    /* construct a datagram */
    DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port);
    socket.send(dp);
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

private void sendByeBye(UPNPMBeanDevice dv) throws IOException {
    InetAddress group = InetAddress.getByName("239.255.255.250");
    java.net.MulticastSocket multi = new java.net.MulticastSocket(bindAddress.getPort());
    multi.setInterface(bindAddress.getAddress());
    multi.setTimeToLive(dv.getSSDPTTL());

    List packets = getByeByeReplyMessages(dv);
    for (int i = 0; i < packets.size(); i++) {
        String packet = (String) packets.get(i);
        if (log.isDebugEnabled())
            log.debug("Sending ssdp:byebye message on 239.255.255.250:1900 multicast address:\n"
                    + packet.toString());
        byte[] pk = packet.getBytes();
        multi.send(new DatagramPacket(pk, pk.length, group, 1900));
    }//from  w  ww .  j  av  a2  s.  c o  m
    multi.close();
}

From source file:snapshotTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;/*w  w  w .  ja v a  2 s .com*/
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    inBuffer = new byte[8192];
    outBuffer = new byte[8192];
    try {
        HttpSession session = RuntimeAccess.getInstance().getSession();
        String sessionUser = (String) session.getAttribute("User");
        if (sessionUser == null) {
            sessionUser = "administrator";
        }
        JSONObject joCmd = new JSONObject();
        JSONObject joAction = new JSONObject(action);
        joCmd.put("sender", sessionUser);
        joCmd.put("target", "SNAPSHOT");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        String actionName = joAction.get("name").toString();
        if (actionName.equals("create")) {
            socket.setSoTimeout(180000);
        } else {
            socket.setSoTimeout(60000);
        }

        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);

        try {
            // send the data
            socket.send(packet2Send);
            receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
            socket.receive(receivedPacket);
            // the server response is...
            result = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
            session.setAttribute("LastActive", System.currentTimeMillis());
        } catch (Exception excep) {
            String msg = excep.getMessage();
            //String msg = excep.toString();
            joCmd.remove("action");
            joAction.put("result", "Error:" + msg);
            joCmd.put("action", joAction);
            result = joCmd.toString();
        }
        socket.close();

    } catch (Exception e) {
        log(ERROR, "callOvnmanager", e);
        return e.toString();
    }
    return result;
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Discovery Process to identify Clusters with in 
 * network.//from  ww w . j  a v  a  2  s .c  om
 * 
 * @throws IOException if occurred during operation
 */
private void doDiscover() throws IOException {

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Wait for Response
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Receive
    resSock.setSoTimeout((int) TIMEOUT);
    try {
        resSock.receive(response);
    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    }

    byte[] data = response.getData();

    byte[] ipBytes = Arrays.copyOfRange(data, 0, 4);
    byte[] portBytes = Arrays.copyOfRange(data, 4, 9);

    InetAddress ip = InetAddress.getByAddress(ipBytes);
    StringBuilder sb = new StringBuilder(ip.getHostAddress());
    sb.append(":");
    for (byte b : portBytes) {
        sb.append(b);
    }

    this.cluster = sb.toString();
}

From source file:org.opennms.netmgt.syslogd.SyslogdEventdLoadIT.java

@Test(timeout = 120000)
@Transactional//from w w w.j  ava 2s .c o m
public void testNGSyslog() throws Exception {
    loadSyslogConfiguration("/etc/syslogd-syslogng-configuration.xml");

    startSyslogdGracefully();

    m_eventCounter.anticipate();

    InetAddress address = InetAddress.getLocalHost();

    // handle an invalid packet
    byte[] bytes = "<34>main: 2010-08-19 localhost foo0: load test 0 on tty1\0".getBytes();
    DatagramPacket pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT);
    new SyslogConnectionHandlerDefaultImpl().handleSyslogConnection(new SyslogConnection(pkt, m_config));

    // handle a valid packet
    bytes = "<34>monkeysatemybrain!\0".getBytes();
    pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT);
    new SyslogConnectionHandlerDefaultImpl().handleSyslogConnection(new SyslogConnection(pkt, m_config));

    m_eventCounter.waitForFinish(120000);

    assertEquals(1, m_eventCounter.getCount());
}