Search in sources :

Example 21 with DatagramSocket

use of java.net.DatagramSocket 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 22 with DatagramSocket

use of java.net.DatagramSocket in project ribbon by Netflix.

the class UdpClientTest method choosePort.

public int choosePort() throws SocketException {
    DatagramSocket serverSocket = new DatagramSocket();
    int port = serverSocket.getLocalPort();
    serverSocket.close();
    return port;
}
Also used : DatagramSocket(java.net.DatagramSocket)

Example 23 with DatagramSocket

use of java.net.DatagramSocket 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 24 with DatagramSocket

use of java.net.DatagramSocket in project Openfire by igniterealtime.

the class ConferenceReceiver method initLoneReceiverChannel.

private void initLoneReceiverChannel(int loneReceiverPort) {
    if (this.loneReceiverPort != loneReceiverPort && loneReceiverChannel != null) {
        close();
    }
    this.loneReceiverPort = loneReceiverPort;
    try {
        selector = Selector.open();
    } catch (IOException e) {
        Logger.println("Conference receiver failed to open selector " + e.getMessage());
        return;
    }
    if (loneReceiverPort == 0) {
        return;
    }
    Logger.println("Init lone channel using port " + loneReceiverPort);
    try {
        loneReceiverChannel = DatagramChannel.open();
        if (Logger.logLevel >= Logger.LOG_INFO) {
            Logger.println("Opened lone receiver channel " + loneReceiverChannel);
        }
    } catch (IOException e) {
        Logger.println("Conference receiver failed to open DatagramChannel " + " " + e.getMessage());
        return;
    }
    try {
        loneReceiverChannel.configureBlocking(false);
    } catch (IOException e) {
        Logger.println("Conference receiver failed to configureBlocking to false " + e.getMessage());
        return;
    }
    DatagramSocket socket = loneReceiverChannel.socket();
    try {
        socket.setReceiveBufferSize(RtpSocket.MAX_RECEIVE_BUFFER);
    } catch (SocketException e) {
        Logger.println("ConferenceReceiver failed to set receive buffer size " + e.getMessage());
        return;
    }
    try {
        socket.setSoTimeout(0);
    } catch (SocketException e) {
        Logger.println("ConferenceReceiver failed to set timeout " + e.getMessage());
        return;
    }
    InetSocketAddress bridgeAddress = Bridge.getLocalBridgeAddress();
    InetSocketAddress isa = new InetSocketAddress(bridgeAddress.getAddress(), loneReceiverPort);
    try {
        socket.bind(isa);
    } catch (IOException e) {
        Logger.println("Conference receiver unable to bind to " + loneReceiverPort + " " + e.getMessage());
        return;
    }
    try {
        SelectionKey selectionKey = loneReceiverChannel.register(selector, SelectionKey.OP_READ);
    } catch (Exception e) {
        Logger.println("Conference receiver unable to register:  " + e.getMessage());
        return;
    }
    memberCount++;
    Logger.println("Lone Channel uses port " + loneReceiverPort);
}
Also used : SocketException(java.net.SocketException) SelectionKey(java.nio.channels.SelectionKey) DatagramSocket(java.net.DatagramSocket) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) IOException(java.io.IOException) SocketException(java.net.SocketException)

Example 25 with DatagramSocket

use of java.net.DatagramSocket in project Openfire by igniterealtime.

the class ConferenceMember method initializeChannel.

private void initializeChannel() throws IOException {
    datagramChannel = conferenceManager.getConferenceReceiver().getChannel(cp);
    if (datagramChannel != null) {
        synchronized (datagramChannel) {
            if (loneRtcpReceiver == null) {
                int rtcpPort = datagramChannel.socket().getLocalPort() + 1;
                Logger.println("Starting lone RtcpReceiver on port " + rtcpPort);
                loneRtcpReceiver = new RtcpReceiver(new DatagramSocket(rtcpPort), true);
            }
            rtcpReceiver = loneRtcpReceiver;
        }
        return;
    }
    /*
	 * We are trying to find a pair of sockets with consecutive port nums.
	 * The first socket must have an even port.
	 *
	 * If we find a socket that we don't like, we have to keep it open
	 * otherwise when we try to find another socket, we may get the same
	 * one as before.
	 *
	 * So we make a list of the bad sockets and close them all
	 * after we're done.
	 */
    ArrayList badChannels = new ArrayList();
    int nextRtpPort = firstRtpPort;
    try {
        while (true) {
            datagramChannel = DatagramChannel.open();
            if (Logger.logLevel >= Logger.LOG_DETAIL) {
                Logger.println("Call " + cp + " Opened datagram channel " + datagramChannel);
            }
            datagramChannel.configureBlocking(false);
            DatagramSocket socket = datagramChannel.socket();
            socket.setReceiveBufferSize(RtpSocket.MAX_RECEIVE_BUFFER);
            socket.setSoTimeout(0);
            InetSocketAddress bridgeAddress = Bridge.getLocalBridgeAddress();
            InetSocketAddress isa = new InetSocketAddress(bridgeAddress.getAddress(), nextRtpPort);
            if (nextRtpPort > 0) {
                nextRtpPort += 2;
                if (lastRtpPort != 0 && (nextRtpPort + 1) > lastRtpPort) {
                    Logger.println("No more RTP ports available, last is " + lastRtpPort);
                    closeBadChannels(badChannels);
                    throw new IOException("No more RTP ports available, last is " + lastRtpPort);
                }
            }
            try {
                socket.bind(isa);
                int localPort = socket.getLocalPort();
                if ((localPort & 1) != 0) {
                    /*
			 * Port is odd, can't use this datagramSocket
			 */
                    if (Logger.logLevel >= Logger.LOG_INFO) {
                        Logger.println("Call " + cp + " skipping DatagramSocket with odd port " + localPort);
                    }
                    badChannels.add(datagramChannel);
                    continue;
                }
                Logger.writeFile("Call " + cp + " RTCP Port " + (localPort + 1));
                rtcpReceiver = new RtcpReceiver(new DatagramSocket(localPort + 1), false);
                break;
            } catch (SocketException e) {
                /*
		     * Couldn't bind, can't use this DatagramSocket.
		     */
                if (Logger.logLevel >= Logger.LOG_INFO) {
                    Logger.println("Call " + cp + " skipping DatagramSocket " + e.getMessage());
                }
                badChannels.add(datagramChannel);
                continue;
            }
        }
    } catch (Exception e) {
        closeBadChannels(badChannels);
        throw new IOException("Call " + cp + " MemberReceiver exception! " + e.getMessage());
    }
    closeBadChannels(badChannels);
    if (Logger.logLevel >= Logger.LOG_INFO) {
        Logger.println("Call " + cp + " port " + datagramChannel.socket().getLocalPort());
    }
}
Also used : SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) RtcpReceiver(com.sun.voip.RtcpReceiver) IOException(java.io.IOException) IOException(java.io.IOException) SocketException(java.net.SocketException) ParseException(java.text.ParseException)

Aggregations

DatagramSocket (java.net.DatagramSocket)266 DatagramPacket (java.net.DatagramPacket)120 IOException (java.io.IOException)98 SocketException (java.net.SocketException)71 InetAddress (java.net.InetAddress)57 InetSocketAddress (java.net.InetSocketAddress)45 UnknownHostException (java.net.UnknownHostException)26 Test (org.junit.Test)25 SocketTimeoutException (java.net.SocketTimeoutException)24 InterruptedIOException (java.io.InterruptedIOException)18 PortUnreachableException (java.net.PortUnreachableException)18 BindException (java.net.BindException)16 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)16 ServerSocket (java.net.ServerSocket)14 DatagramChannel (java.nio.channels.DatagramChannel)13 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 MulticastSocket (java.net.MulticastSocket)10 SocketAddress (java.net.SocketAddress)8 ByteBuffer (java.nio.ByteBuffer)8 SmallTest (android.test.suitebuilder.annotation.SmallTest)5