Search in sources :

Example 16 with DatagramPacket

use of java.net.DatagramPacket in project malmo by Microsoft.

the class UDPSocketHelper method sendUDPString.

/** Send string over UDP to the specified address via the specified port.
     * @param message string to be sent over UDP
     * @param address address to send the message to
     * @param port port number to use
     * @return true if message was successfully sent
     */
public static boolean sendUDPString(String message, InetAddress address, int port) {
    DatagramPacket packet = null;
    boolean succeeded = true;
    packet = new DatagramPacket(message.getBytes(), message.length(), address, port);
    DatagramSocket socket = null;
    try {
        socket = new DatagramSocket();
    } catch (SocketException e1) {
        System.out.println("Error creating UDP socket");
        succeeded = false;
    }
    if (socket != null) {
        try {
            socket.send(packet);
        } catch (IOException e) {
            System.out.println("Error sending UDP packet");
            succeeded = false;
        }
        socket.close();
    }
    return succeeded;
}
Also used : SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException)

Example 17 with DatagramPacket

use of java.net.DatagramPacket in project actor-platform by actorapp.

the class SntpClient method requestTime.

/**
     * Sends an SNTP request to the given host and processes the response.
     *
     * @param host    host name of the server.
     * @param timeout network timeout in milliseconds.
     * @return true if the transaction was successful.
     */
public boolean requestTime(String host, int timeout) {
    DatagramSocket socket = null;
    try {
        socket = new DatagramSocket();
        socket.setSoTimeout(timeout);
        InetAddress address = InetAddress.getByName(host);
        byte[] buffer = new byte[NTP_PACKET_SIZE];
        DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
        // set mode = 3 (client) and version = 3
        // mode is in low 3 bits of first byte
        // version is in bits 3-5 of first byte
        buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
        // get current time and write it to the request packet
        long requestTime = System.currentTimeMillis();
        long requestTicks = SystemClock.elapsedRealtime();
        writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
        socket.send(request);
        // read the response
        DatagramPacket response = new DatagramPacket(buffer, buffer.length);
        socket.receive(response);
        long responseTicks = SystemClock.elapsedRealtime();
        long responseTime = requestTime + (responseTicks - requestTicks);
        // extract the results
        long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
        long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
        long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
        long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
        // receiveTime = originateTime + transit + skew
        // responseTime = transmitTime + transit - skew
        // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
        //             = ((originateTime + transit + skew - originateTime) +
        //                (transmitTime - (transmitTime + transit - skew)))/2
        //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
        //             = (transit + skew - transit + skew)/2
        //             = (2 * skew)/2 = skew
        mClockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;
        // if (false) Log.d(TAG, "round trip: " + roundTripTime + " ms");
        // if (false) Log.d(TAG, "clock offset: " + clockOffset + " ms");
        // save our results - use the times on this side of the network latency
        // (response rather than request time)
        mNtpTime = responseTime + mClockOffset;
        mNtpTimeReference = responseTicks;
        mRoundTripTime = roundTripTime;
    } catch (Exception e) {
        return false;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
    return true;
}
Also used : DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) InetAddress(java.net.InetAddress)

Example 18 with DatagramPacket

use of java.net.DatagramPacket in project jmonkeyengine by jMonkeyEngine.

the class UdpEndpoint method send.

public void send(ByteBuffer data) {
    if (!isConnected()) {
        throw new KernelException("Endpoint is not connected:" + this);
    }
    try {
        DatagramPacket p = new DatagramPacket(data.array(), data.position(), data.remaining(), address);
        // Just queue it up for the kernel threads to write
        // out
        kernel.enqueueWrite(this, p);
    //socket.send(p);
    } catch (Exception e) {
        if (e instanceof SocketException) {
            throw new KernelException("Error sending datagram to:" + address, e);
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}
Also used : SocketException(java.net.SocketException) DatagramPacket(java.net.DatagramPacket) KernelException(com.jme3.network.kernel.KernelException) SocketException(java.net.SocketException) KernelException(com.jme3.network.kernel.KernelException) IOException(java.io.IOException)

Example 19 with DatagramPacket

use of java.net.DatagramPacket in project Smack by igniterealtime.

the class TcpUdpBridgeClient method startBridge.

public void startBridge() {
    final Thread process = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                OutputStream out = localTcpSocket.getOutputStream();
                while (true) {
                    byte[] b = new byte[500];
                    DatagramPacket p = new DatagramPacket(b, 500);
                    localUdpSocket.receive(p);
                    if (p.getLength() == 0)
                        continue;
                    LOGGER.fine("UDP Client Received and Sending to TCP Server:" + new String(p.getData(), 0, p.getLength(), "UTF-8"));
                    out.write(p.getData(), 0, p.getLength());
                    out.flush();
                    LOGGER.fine("Client Flush");
                }
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, "exception", e);
            }
        }
    });
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                InputStream in = localTcpSocket.getInputStream();
                InetAddress remoteHost = InetAddress.getByName(remoteUdpHost);
                process.start();
                while (true) {
                    byte[] b = new byte[500];
                    int s = in.read(b);
                    //if (s == -1) continue;
                    LOGGER.fine("TCP Client:" + new String(b, 0, s, "UTF-8"));
                    DatagramPacket udpPacket = new DatagramPacket(b, s);
                    udpPacket.setAddress(remoteHost);
                    udpPacket.setPort(remoteUdpPort);
                    localUdpSocket.send(udpPacket);
                }
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, "exception", e);
            }
        }
    }).start();
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 20 with DatagramPacket

use of java.net.DatagramPacket in project Smack by igniterealtime.

the class TcpUdpBridgeServer method startBridge.

public void startBridge() {
    final Thread process = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                OutputStream out = localTcpSocket.getOutputStream();
                while (true) {
                    byte[] b = new byte[500];
                    DatagramPacket p = new DatagramPacket(b, 500);
                    localUdpSocket.receive(p);
                    if (p.getLength() == 0)
                        continue;
                    LOGGER.fine("UDP Server Received and Sending to TCP Client:" + new String(p.getData(), 0, p.getLength(), "UTF-8"));
                    out.write(p.getData(), 0, p.getLength());
                    out.flush();
                    LOGGER.fine("Server Flush");
                }
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, "exception", e);
            }
        }
    });
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                localTcpSocket = serverTcpSocket.accept();
                process.start();
                InputStream in = localTcpSocket.getInputStream();
                InetAddress remoteHost = InetAddress.getByName(remoteUdpHost);
                while (true) {
                    byte[] b = new byte[500];
                    int s = in.read(b);
                    //if (s == -1) continue;
                    LOGGER.fine("TCP Server:" + new String(b, 0, s, "UTF-8"));
                    DatagramPacket udpPacket = new DatagramPacket(b, s);
                    udpPacket.setAddress(remoteHost);
                    udpPacket.setPort(remoteUdpPort);
                    localUdpSocket.send(udpPacket);
                }
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, "exception", e);
            }
        }
    }).start();
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Aggregations

DatagramPacket (java.net.DatagramPacket)302 IOException (java.io.IOException)126 DatagramSocket (java.net.DatagramSocket)121 InetAddress (java.net.InetAddress)69 SocketException (java.net.SocketException)43 Test (org.junit.Test)35 InetSocketAddress (java.net.InetSocketAddress)34 SocketTimeoutException (java.net.SocketTimeoutException)30 UnknownHostException (java.net.UnknownHostException)21 MulticastSocket (java.net.MulticastSocket)18 InterruptedIOException (java.io.InterruptedIOException)17 SocketAddress (java.net.SocketAddress)15 ByteBuffer (java.nio.ByteBuffer)11 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 SyslogConnection (org.opennms.netmgt.syslogd.api.SyslogConnection)11 PortUnreachableException (java.net.PortUnreachableException)9 ArrayList (java.util.ArrayList)9 SyslogMessageLogDTO (org.opennms.netmgt.syslogd.api.SyslogMessageLogDTO)8 BindException (java.net.BindException)7 Transactional (org.springframework.transaction.annotation.Transactional)7