Java 8 DatagramSocket - top ranked examples from Open Source projects

These code examples were ranked by Codota’s semantic indexing as the best open source examples for Java 8 DatagramSocket class.

This code example shows how to use the following methods:
    @Test 
    public void createDatagram() throws IOException { 
 
        DatagramSocket socket1 = new DatagramSocket();
        DatagramSocket socket2 = new DatagramSocket();
        DatagramSocket socket3 = new DatagramSocket();
        DatagramSocket socket4 = new DatagramSocket();
        InetAddress localhost = InetAddress.getLocalHost();
        SocketAddress socketAddress = new InetSocketAddress(localhost, 1);
 
        when(this.factory.createDatagramSocket("test")).thenReturn(socket1);
        when(this.factory.createDatagramSocket("test", 1)).thenReturn(socket2);
        when(this.factory.createDatagramSocket("test", socketAddress)).thenReturn(socket3);
        when(this.factory.createDatagramSocket("test", 1, localhost)).thenReturn(socket4);
 
        DatagramSocket result1 = this.subject.createDatagramSocket("test");
        DatagramSocket result2 = this.subject.createDatagramSocket("test", 1);
        DatagramSocket result3 = this.subject.createDatagramSocket("test", socketAddress);
        DatagramSocket result4 = this.subject.createDatagramSocket("test", 1, localhost);
 

9
CodeRank
This code example shows how to use the following methods:connect, setSoTimeout
public class RtpSocket { 
  private final byte [] buf = new byte[4096];
  private DatagramSocket socket;
 
  public RtpSocket(int localPort, InetSocketAddress remoteAddress) throws SocketException {
    socket = new DatagramSocket(localPort);
    socket.setSoTimeout(1);
    socket.connect(new InetSocketAddress(remoteAddress.getAddress().getHostAddress(), remoteAddress.getPort()));
    Log.d( "RtpSocket", "Connected to: " + remoteAddress.getAddress().getHostAddress() );
  } 
 
  public void setTimeout(int timeoutMillis) {
    try { 
      socket.setSoTimeout(timeoutMillis);
    } catch (SocketException e) {
      Log.w("RtpSocket", e);
    } 
  } 
 
  private long totalSendTime = 0;
8
CodeRank
This code example shows how to use the following methods:close, isClosed
	// =========================================================== 
	// Methods 
	// =========================================================== 
 
	public static final void closeSocket(final DatagramSocket pDatagramSocket) {
		if(pDatagramSocket != null && !pDatagramSocket.isClosed()) {
			pDatagramSocket.close();
		} 
	} 
 
	public static final void closeSocket(final Socket pSocket) {
		if(pSocket != null && !pSocket.isClosed()) {
			try { 
				pSocket.close();
			} catch (final IOException e) {
				Debug.e(e);
			} 
		} 
	} 
 
8
CodeRank
This code example shows how to use the following methods:close, setReuseAddress
			ServerSocket ss = null;
			DatagramSocket ds = null;
			try { 
				ss = new ServerSocket(port);
				ss.setReuseAddress(true);
				ds = new DatagramSocket(port);
				ds.setReuseAddress(true);
				return true; 
			} catch (IOException e) {
			} finally { 
				if (ds != null) {
					ds.close();
				} 
 
				if (ss != null) {
					try { 
						ss.close();
					} catch (IOException e) {
						/* should not be thrown */ 
					} 
6
CodeRank
This code example shows how to use the following methods:connect, isBound, isConnected
/** 
 * A simple test designed to conduct a DTLS handshake with an external DTLS server. 
 * <p/> 
 * Please refer to GnuTLSSetup.txt or OpenSSLSetup.txt, and x509-*.pem files in this package for 
 * help configuring an external DTLS server. 
 */ 
public class DTLSClientTest 
{ 
    private static final SecureRandom secureRandom = new SecureRandom();
 
    public static void main(String[] args)
        throws Exception 
    { 
        InetAddress address = InetAddress.getLocalHost();
        int port = 5556;
 
        TlsSession session = createSession(address, port);
 
        MockDTLSClient client = new MockDTLSClient(session);
 

7
CodeRank
This code example shows how to use the following methods:close, receive, setSoTimeout
import java.net.SocketTimeoutException; 
 
public class DatagramTimeout { 
    public static void main(String[] args) throws Exception {
        boolean success = false;
        DatagramSocket sock = new DatagramSocket();
 
        try { 
            DatagramPacket p;
            byte[] buffer = new byte[50];
            p = new DatagramPacket(buffer, buffer.length);
            sock.setSoTimeout(2);
            sock.receive(p);
        } catch (SocketTimeoutException e) {
            success = true;
        } finally { 
            sock.close();
        } 
        if (!success)
            throw new RuntimeException("Socket timeout failure.");

7
CodeRank
This code example shows how to use the following methods:close
        } 
 
        @Override 
        void close() { 
            closed.set(true);
            socket.close();
        } 
 
        @Override 
        public void run(){ 
 
            while (!closed.get()){
                try { 
                    DatagramPacket packet = new DatagramPacket(new byte[2048], 2048);
                    socket.receive(packet);
                    byte[] bytes = new byte[packet.getLength()];
                    System.arraycopy(packet.getData(), 0, bytes, 0, packet.getLength());
                    receivedData.add(bytes);
                } catch (IOException e) {
                    if (!closed.get()){
7
CodeRank
This code example shows how to use the following methods:close, send
		try { 
			byte[] magic = { 'a', 'r', 'd', 'u', 'i', 'n', 'o' };
			DatagramPacket packet;
			packet = new DatagramPacket(magic, magic.length, _addr, _port);
 
			DatagramSocket socket = new DatagramSocket();
			socket.send(packet);
			socket.close();
			System.out.println("Packet sent.");
		} catch(SocketException e) {
			e.printStackTrace();
		} catch(IOException e) {
			e.printStackTrace();
		} 
	} 
 
} 
7
CodeRank
This code example shows how to use the following methods:receive, setSoTimeout
    } 
 
    public int receive(byte[] buf, int off, int len, int waitMillis)
        throws IOException 
    { 
        socket.setSoTimeout(waitMillis);
        DatagramPacket packet = new DatagramPacket(buf, off, len);
        socket.receive(packet);
        return packet.getLength();
    } 
 
    public void send(byte[] buf, int off, int len)
        throws IOException 
    { 
        if (len > getSendLimit())
        { 
            /* 
             * RFC 4347 4.1.1. "If the application attempts to send a record larger than the MTU, 
             * the DTLS implementation SHOULD generate an error, thus avoiding sending a packet 
             * which will be fragmented." 
7
CodeRank
This code example shows how to use the following methods:close, receive, send, setSoTimeout
     * @param timeout network timeout in milliseconds. 
     * @return true if the transaction was successful. 
     */ 
    public boolean requestTime(String host, int timeout) {
        try { 
            DatagramSocket 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);

6
CodeRank

Related Java 8 DatagramSocket Questions & Answers:

See Code Examples for Java 8 DatagramSocket Methods: