Package java.net

Examples of java.net.DatagramSocket


    }

    try {
      // First, close the previous connection if any.
      cleanUp();
      outSocket = new DatagramSocket();
      outSocket.connect(address, port);
    } catch (IOException e) {
      getLogger().error(
        "Could not open UDP Socket for sending.", e);
      inError = true;
View Full Code Here


        if (myQuorumAddr == null) {
            throw new RuntimeException("My id " + myid + " not in the peer list");
        }
        if (electionType == 0) {
            try {
                udpSocket = new DatagramSocket(myQuorumAddr.getPort());
                responder = new ResponderThread();
                responder.start();
            } catch (SocketException e) {
                throw new RuntimeException(e);
            }
View Full Code Here

            LOGGER.error(msg, ex);
            throw new AppenderRuntimeException(msg, ex);
        }

        try {
            ds = new DatagramSocket();
        } catch (final SocketException ex) {
            final String msg = "Could not instantiate DatagramSocket to " + host;
            LOGGER.error(msg, ex);
            throw new AppenderRuntimeException(msg, ex);
        }
View Full Code Here

     *            to listen on.
     * @throws IOException
     *             If an error occurs.
     */
    public UDPSocketServer(final int port) throws IOException {
        server = new DatagramSocket(port);
        if (logger == null) {
            logger = LogManager.getLogger(this);
            // logger = LogManager.getLogger(getClass().getName() + '.' + port);
        }
    }
View Full Code Here

    slopeTable = getAttributeTable(SLOPE_PROPERTY);
    tmaxTable  = getAttributeTable(TMAX_PROPERTY);
    dmaxTable  = getAttributeTable(DMAX_PROPERTY);
       
    try {
      datagramSocket = new DatagramSocket();
    }
    catch (SocketException se) {
      se.printStackTrace();
    }
  }
View Full Code Here

   
    ChukwaAgent agent = new ChukwaAgent(conf);
    String ADAPTORID = "adaptor_test" + System.currentTimeMillis();
    String STR = "test data";
    int PORTNO = 9878;
    DatagramSocket send = new DatagramSocket();
    byte[] buf = STR.getBytes();
    DatagramPacket p = new DatagramPacket(buf, buf.length);
    p.setSocketAddress(new InetSocketAddress("127.0.0.1",PORTNO));
   
    assertEquals(0, agent.adaptorCount());
    String name =agent.processAddCommand("add "+ ADAPTORID + " = "+adaptor+" UDPAdaptor raw "+PORTNO+ " 0");
    assertEquals(name, ADAPTORID);
    Thread.sleep(500);
    send.send(p);
   
    for(int i=0; i< 5; ++i) {
      Chunk c = chunks.waitForAChunk(5000);
      System.out.println("received " + i);
      assertNotNull(c);
      String dat = new String(c.getData());
      assertTrue(dat.equals(STR));
      assertTrue(c.getDataType().equals("raw"));
      assertEquals(c.getSeqID(), STR.length());
     
      agent.stopAdaptor(name, AdaptorShutdownPolicy.RESTARTING);
      Thread.sleep(500); //for socket to deregister
      name =agent.processAddCommand("add "+ADAPTORID + " = "+adaptor+" UDPAdaptor raw "+PORTNO + " 0");
      assertEquals(name, ADAPTORID);
    }
    Chunk c = chunks.waitForAChunk(5000);

    Thread.sleep(500);
   
    buf = "different data".getBytes();
    p = new DatagramPacket(buf, buf.length);  
    p.setSocketAddress(new InetSocketAddress("127.0.0.1",PORTNO));
    send.send(p);
    c = chunks.waitForAChunk(5000);
    assertNotNull(c);
    assertEquals(buf.length + STR.length(), c.getSeqID());
   
    agent.stopAdaptor(name, true);
View Full Code Here

  private void runKeepFieldsTest(boolean keepFields) throws IOException {
    init(keepFields);
    source.start();
    // Write some message to the syslog port
    DatagramSocket syslogSocket;
    DatagramPacket datagramPacket;
    datagramPacket = new DatagramPacket(bodyWithTandH.getBytes(),
      bodyWithTandH.getBytes().length,
      InetAddress.getLocalHost(), source.getSourcePort());
    for (int i = 0; i < 10 ; i++) {
      syslogSocket = new DatagramSocket();
      syslogSocket.send(datagramPacket);
      syslogSocket.close();
    }

    List<Event> channelEvents = new ArrayList<Event>();
    Transaction txn = channel.getTransaction();
    txn.begin();
View Full Code Here

    source.start();
    // Write some message to the syslog port

    byte[] largePayload = getPayload(1000).getBytes();

    DatagramSocket syslogSocket;
    DatagramPacket datagramPacket;
    datagramPacket = new DatagramPacket(largePayload,
            1000,
            InetAddress.getLocalHost(), source.getSourcePort());
    for (int i = 0; i < 10 ; i++) {
      syslogSocket = new DatagramSocket();
      syslogSocket.send(datagramPacket);
      syslogSocket.close();
    }

    List<Event> channelEvents = new ArrayList<Event>();
    Transaction txn = channel.getTransaction();
    txn.begin();
View Full Code Here

    void mockServer() throws InterruptedException, IOException {
        byte b[] = new byte[36];
        ByteBuffer responseBuffer = ByteBuffer.wrap(b);
        DatagramPacket packet = new DatagramPacket(b, b.length);
        QuorumServer server = peers.get(Long.valueOf(2));
        DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
        LOG.info("In MockServer");
        mockLatch.countDown();
        Vote current = new Vote(2, 1);
        for (int i=0;i<2;++i) {
            udpSocket.receive(packet);
            responseBuffer.rewind();
            LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
            LOG.info("From " + packet.getSocketAddress());
            responseBuffer.clear();
            responseBuffer.getInt(); // Skip the xid
            responseBuffer.putLong(2);

            responseBuffer.putLong(current.getId());
            responseBuffer.putLong(current.getZxid());
            packet.setData(b);
            udpSocket.send(packet);
        }
    }
View Full Code Here

            byte requestBytes[] = new byte[4];
            ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
            byte responseBytes[] = new byte[28];
            ByteBuffer responseBuffer = ByteBuffer.wrap(responseBytes);
            /* The current vote for the leader. Initially me! */
            DatagramSocket s = null;
            try {
                s = new DatagramSocket();
                s.setSoTimeout(200);
            } catch (SocketException e1) {
                LOG.error("Socket exception when creating socket for leader election", e1);
                System.exit(4);
            }
            DatagramPacket requestPacket = new DatagramPacket(requestBytes,
                    requestBytes.length);
            DatagramPacket responsePacket = new DatagramPacket(responseBytes,
                    responseBytes.length);
            int xid = epochGen.nextInt();
            while (self.isRunning()) {
                HashMap<InetSocketAddress, Vote> votes =
                    new HashMap<InetSocketAddress, Vote>(self.getVotingView().size());

                requestBuffer.clear();
                requestBuffer.putInt(xid);
                requestPacket.setLength(4);
                HashSet<Long> heardFrom = new HashSet<Long>();
                for (QuorumServer server :
                    self.getVotingView().values())
                {
                    LOG.info("Server address: " + server.addr);
                    try {
                        requestPacket.setSocketAddress(server.addr);
                    } catch (IllegalArgumentException e) {
                        // Sun doesn't include the address that causes this
                        // exception to be thrown, so we wrap the exception
                        // in order to capture this critical detail.
                        throw new IllegalArgumentException(
                                "Unable to set socket address on packet, msg:"
                                + e.getMessage() + " with addr:" + server.addr,
                                e);
                    }

                    try {
                        s.send(requestPacket);
                        responsePacket.setLength(responseBytes.length);
                        s.receive(responsePacket);
                        if (responsePacket.getLength() != responseBytes.length) {
                            LOG.error("Got a short response: "
                                    + responsePacket.getLength());
                            continue;
                        }
                        responseBuffer.clear();
                        int recvedXid = responseBuffer.getInt();
                        if (recvedXid != xid) {
                            LOG.error("Got bad xid: expected " + xid
                                    + " got " + recvedXid);
                            continue;
                        }
                        long peerId = responseBuffer.getLong();
                        heardFrom.add(peerId);
                        //if(server.id != peerId){
                        Vote vote = new Vote(responseBuffer.getLong(),
                                responseBuffer.getLong());
                        InetSocketAddress addr =
                            (InetSocketAddress) responsePacket
                            .getSocketAddress();
                        votes.put(addr, vote);
                        //}
                    } catch (IOException e) {
                        LOG.warn("Ignoring exception while looking for leader",
                                e);
                        // Errors are okay, since hosts may be
                        // down
                    }
                }

                ElectionResult result = countVotes(votes, heardFrom);

                /**
                 * This is the only difference from LeaderElection - wait for
                 * this latch on the first time through this method. This ensures
                 * that the first round of voting happens before setCurrentVote
                 * is called below.
                 */
                LOG.info("Waiting for first round of voting to complete");
                latch.countDown();
                Assert.assertTrue("Thread timed out waiting for latch",
                        latch.await(10000, TimeUnit.MILLISECONDS));

                // ZOOKEEPER-569:
                // If no votes are received for live peers, reset to voting
                // for ourselves as otherwise we may hang on to a vote
                // for a dead peer
                if (result.numValidVotes == 0) {
                    self.setCurrentVote(new Vote(self.getId(),
                            self.getLastLoggedZxid()));
                } else {
                    if (result.winner.getId() >= 0) {
                        self.setCurrentVote(result.vote);
                        // To do: this doesn't use a quorum verifier
                        if (result.winningCount > (self.getVotingView().size() / 2)) {
                            self.setCurrentVote(result.winner);
                            s.close();
                            Vote current = self.getCurrentVote();
                            LOG.info("Found leader: my type is: " + self.getLearnerType());
                            /*
                             * We want to make sure we implement the state machine
                             * correctly. If we are a PARTICIPANT, once a leader
View Full Code Here

TOP

Related Classes of java.net.DatagramSocket

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.