Example usage for java.net DatagramSocket connect

List of usage examples for java.net DatagramSocket connect

Introduction

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

Prototype

public void connect(SocketAddress addr) throws SocketException 

Source Link

Document

Connects this socket to a remote socket address (IP address + port number).

Usage

From source file:lockstep.LockstepServer.java

/**
 * Implements the handshake protocol server side, setting up the UDP 
 * connection, queues and threads for a specific client.
 * To be run in parallel threads, one for each client, as they need
 * to synchronize to correctly setup the lockstep protocol.
 * It signals success through a latch or failure through interruption to the
 * server thread.//from  w  w w  .j a v a 2s  .  com
 * 
 * @param tcpSocket Connection with the client, to be used in handshake only
 * @param firstFrameNumber Frame number to initialize the lockstep protocol
 * @param barrier Used for synchronization with concurrent handshake sessions
 * @param latch Used to signal the successful completion of the handshake session.
 * @param server Used to signal failure of the handshake sessions, via interruption.
 */
private void serverHandshakeProtocol(Socket tcpSocket, int firstFrameNumber, CyclicBarrier barrier,
        CountDownLatch latch, LockstepServer server) {
    try (ObjectOutputStream oout = new ObjectOutputStream(tcpSocket.getOutputStream());) {
        oout.flush();
        try (ObjectInputStream oin = new ObjectInputStream(tcpSocket.getInputStream());) {
            //Receive hello message from client and reply
            LOG.info("Waiting an hello from " + tcpSocket.getInetAddress().getHostAddress());
            oout.flush();
            ClientHello hello = (ClientHello) oin.readObject();
            LOG.info("Received an hello from " + tcpSocket.getInetAddress().getHostAddress());
            DatagramSocket udpSocket = new DatagramSocket();
            openSockets.add(udpSocket);
            InetSocketAddress clientUDPAddress = new InetSocketAddress(
                    tcpSocket.getInetAddress().getHostAddress(), hello.clientUDPPort);
            udpSocket.connect(clientUDPAddress);

            int assignedClientID;
            do {
                assignedClientID = (new Random()).nextInt(100000) + 10000;
            } while (!this.clientIDs.add(assignedClientID));

            LOG.info("Assigned hostID " + assignedClientID + " to "
                    + tcpSocket.getInetAddress().getHostAddress() + ", sending helloReply");
            ServerHelloReply helloReply = new ServerHelloReply(udpSocket.getLocalPort(), assignedClientID,
                    clientsNumber, firstFrameNumber);
            oout.writeObject(helloReply);

            ConcurrentHashMap<Integer, TransmissionQueue> clientTransmissionFrameQueues = new ConcurrentHashMap<>();
            this.transmissionFrameQueueTree.put(assignedClientID, clientTransmissionFrameQueues);

            ACKSet clientAckQueue = new ACKSet();
            ackQueues.put(assignedClientID, clientAckQueue);

            clientReceiveSetup(assignedClientID, udpSocket, firstFrameNumber, clientTransmissionFrameQueues);

            barrier.await();

            //Send second reply
            ClientsAnnouncement announcement = new ClientsAnnouncement();
            announcement.clientIDs = ArrayUtils.toPrimitive(this.clientIDs.toArray(new Integer[0]));
            oout.writeObject(announcement);

            clientTransmissionSetup(assignedClientID, firstFrameNumber, udpSocket,
                    clientTransmissionFrameQueues);

            //Wait for other handshakes to reach final step
            barrier.await();
            oout.writeObject(new SimulationStart());

            //Continue with execution
            latch.countDown();
        }
    } catch (IOException | ClassNotFoundException ioEx) {
        LOG.fatal("Exception at handshake with client");
        LOG.fatal(ioEx);
        server.interrupt();
    } catch (InterruptedException | BrokenBarrierException inEx) {
        //Interruptions come from failure in parallel handshake sessions, and signal termination
    }
}

From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

@Test
public void datagramPacket_length_zero() {
    UDPReceiver receiver = null;//from   w ww  . j  ava 2 s .c  o  m
    DatagramSocket datagramSocket = null;

    CountDownLatch latch = new CountDownLatch(1);
    Executor mockExecutor = mockDispatchWorker(latch);

    PacketHandlerFactory packetHandlerFactory = mock(PacketHandlerFactory.class);
    when(packetHandlerFactory.createPacketHandler()).thenReturn(loggingPacketHandler);

    try {
        InetSocketAddress bindAddress = new InetSocketAddress(ADDRESS, PORT);
        ObjectPoolFactory<DatagramPacket> packetFactory = new DatagramPacketFactory();
        ObjectPool<DatagramPacket> pool = new DefaultObjectPool<>(packetFactory, 10);
        receiver = new UDPReceiver("test", packetHandlerFactory, mockExecutor, 8, bindAddress, pool) {
            @Override
            boolean validatePacket(DatagramPacket packet) {
                interceptValidatePacket(packet);
                return super.validatePacket(packet);
            }
        };
        receiver.start();

        datagramSocket = new DatagramSocket();
        datagramSocket.connect(new InetSocketAddress(ADDRESS, PORT));

        datagramSocket.send(new DatagramPacket(new byte[0], 0));
        datagramSocket.send(new DatagramPacket(new byte[1], 1));

        Assert.assertTrue(latch.await(30000, TimeUnit.MILLISECONDS));
        Assert.assertEquals(zeroPacketCounter.get(), 1);
        Mockito.verify(mockExecutor).execute(any(Runnable.class));
    } catch (Exception e) {
        logger.debug(e.getMessage(), e);
        Assert.fail(e.getMessage());
    } finally {
        if (receiver != null) {
            receiver.shutdown();
        }
        IOUtils.closeQuietly(datagramSocket);

    }
}