/**
   * Copies the properties of a specific <tt>DatagramPacket</tt> to another <tt>DatagramPacket</tt>.
   * The property values are not cloned.
   *
   * @param src the <tt>DatagramPacket</tt> which is to have its properties copied to <tt>dest</tt>
   * @param dest the <tt>DatagramPacket</tt> which is to have its properties set to the value of the
   *     respective properties of <tt>src</tt>
   */
  public static void copy(DatagramPacket src, DatagramPacket dest) {
    synchronized (dest) {
      dest.setAddress(src.getAddress());
      dest.setPort(src.getPort());

      byte[] srcData = src.getData();

      if (srcData == null) dest.setLength(0);
      else {
        byte[] destData = dest.getData();

        if (destData == null) dest.setLength(0);
        else {
          int destOffset = dest.getOffset();
          int destLength = destData.length - destOffset;
          int srcLength = src.getLength();

          if (destLength >= srcLength) destLength = srcLength;
          else if (logger.isLoggable(Level.WARNING)) {
            logger.log(Level.WARNING, "Truncating received DatagramPacket data!");
          }
          System.arraycopy(srcData, src.getOffset(), destData, destOffset, destLength);
          dest.setLength(destLength);
        }
      }
    }
  }
Beispiel #2
0
  private void sendPacket() {

    long start = System.nanoTime();
    byte[] hpsdrdata = getPacketToSend();

    try {
      if (rxdatagram == null)
        rxdatagram =
            new DatagramPacket(hpsdrdata, hpsdrdata.length, this.remoteAddress, this.remotePort);
      else {
        rxdatagram.setData(hpsdrdata);
        rxdatagram.setLength(hpsdrdata.length);
        rxdatagram.setAddress(this.remoteAddress);
        rxdatagram.setPort(this.remotePort);
      }

      socket.setReuseAddress(true);
      socket.send(rxdatagram);

      double time = (System.nanoTime() - start) / 100000d;
      // if (time > 50.0)
      // System.out.println("samen stellen packet " + time + " msec");

    } catch (SocketException se) {
      System.out.println("se exception");
    } catch (IOException ioe) {
      System.out.println("io exception");
    }
  }
Beispiel #3
0
 public static void main(String[] args) throws IOException {
   String strSend = "Hello ANDROID";
   byte[] buf = new byte[1024];
   // 服务端在3000端口监听接收到的数据
   DatagramSocket ds = new DatagramSocket(3000);
   // 接收从客户端发送过来的数据
   DatagramPacket dpReceive = new DatagramPacket(buf, 1024);
   System.out.println("server is on,waiting for client to send data......");
   boolean f = true;
   while (f) {
     // 服务器端接收来自客户端的数据
     ds.receive(dpReceive);
     System.out.println("server received data from client:");
     String strReceive =
         new String(dpReceive.getData(), 0, dpReceive.getLength())
             + " from "
             + dpReceive.getAddress().getHostAddress()
             + ":"
             + dpReceive.getPort();
     System.out.println(strReceive);
     // 数据发动到客户端的3000端口
     DatagramPacket dpSend =
         new DatagramPacket(strSend.getBytes(), strSend.length(), dpReceive.getAddress(), 9000);
     ds.send(dpSend);
     // 由于dp_receive在接收了数据之后,其内部消息长度值会变为实际接收的消息的字节数,
     // 所以这里要将dp_receive的内部消息长度重新置为1024
     dpReceive.setLength(1024);
   }
   ds.close();
 }
Beispiel #4
0
  public static void doEcho(int port) throws IOException {
    byte[] buf = new byte[BUF_SIZE];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    DatagramSocket sock = new DatagramSocket(port);

    System.out.println(
        "Starting UDP echo on"
            + sock.getLocalAddress().getHostAddress()
            + ":"
            + sock.getLocalPort());
    while (true) {
      try {
        sock.receive(packet);
        sock.send(packet);
        System.out.print(
            "UDP From: "
                + packet.getAddress().getHostAddress()
                + ":"
                + packet.getPort()
                + "\n"
                + new String(packet.getData(), 0, packet.getLength())
                + "\n");
        System.out.flush();

        packet.setLength(buf.length);
        // packet = new DatagramPacket(buf,buf.length);
      } catch (IOException io_ex) {
      }
    }
  }
Beispiel #5
0
  public static void main(String[] args) throws Exception {

    int localPort = 40000;
    int port = 50000;
    String host = "localhost";
    String msg = "Hallo World! Random: " + rndmFromRage(0, 99);

    if (args.length == 4) {
      localPort = Integer.parseInt(args[0]);
      host = args[1];
      port = Integer.parseInt(args[2]);
      msg = args[3];
    }

    System.out.println("(Sender) starting on port: " + localPort);

    try (DatagramSocket socket = new DatagramSocket(localPort)) {

      System.out.println("(Sender) sending: '" + msg + "' to: " + host + ":" + port);

      InetAddress addr = InetAddress.getByName(host);
      DatagramPacket packet = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE, addr, port);
      byte[] data = msg.getBytes();
      packet.setData(data);
      packet.setLength(data.length);

      socket.send(packet);
    }
  }
Beispiel #6
0
  public void run() {
    DatagramPacket dataPacket = null;

    try {
      udpSocket = new DatagramSocket(DEFAULT_PORT);

      dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
      byte[] data = dataString.getBytes();
      dataPacket.setData(data);
      dataPacket.setLength(data.length);
      dataPacket.setPort(DEFAULT_PORT);

      InetAddress broadcastAddr;
      String ipAddress = iA.getIpAddress();
      broadcastAddr = InetAddress.getByName(ipAddress);
      dataPacket.setAddress(broadcastAddr);
    } catch (Exception e) {
      Log.e(LOG_TAG, e.toString());
    }
    // while( start ){
    try {
      udpSocket.send(dataPacket);
      sleep(10);
    } catch (Exception e) {
      Log.e(LOG_TAG, e.toString());
    }
    // }

    udpSocket.close();
  }
  public void run() {

    try {

      socket = new DatagramSocket(port);

      byte[] buffer = new byte[maxPacketSize];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

      while (isRunning) {
        socket.receive(packet);
        HaleUDPInputDeviceEvent event =
            new HaleUDPInputDeviceEvent(packet.getAddress().getHostName(), packet.getData());
        if (event.isValid()) {
          this.notifyListeners(event);
          logger.debug(event);
        } else {
          logger.error("Invalid HaleUDPSensorEvent: " + event);
        }
        packet.setLength(buffer.length);
      }

    } catch (SocketException e) {
      if (isRunning) {
        logger.error(e);
      }
    } catch (IOException e) {
      logger.error(e);
    } finally {
      isRunning = false;
      thread = null;
    }
  }
Beispiel #8
0
  public static boolean sessionDeleteClient(SessionTable session, Server e) throws IOException {
    DatagramSocket rpcSocket = new DatagramSocket();
    rpcSocket.setSoTimeout(2000); // Timeout after 2 seconds
    String callID = UUID.randomUUID().toString(); // generate unique id for call
    byte[] outBuf = new byte[512];
    // fill outBuf with callId, operationSESSIONDelete, sessionID, sessionVersionNum
    String outStr = callID + "+2+" + session.getSid() + "+" + session.getVersion();
    outBuf = string2byte(outStr);
    //	for(Server e : s){
    DatagramPacket sendPkt = new DatagramPacket(outBuf, outBuf.length, e.ip, e.port);
    rpcSocket.send(sendPkt);
    //	}

    byte[] inBuf = new byte[512];
    DatagramPacket recvPkt = new DatagramPacket(inBuf, inBuf.length);
    try {
      do {
        recvPkt.setLength(inBuf.length);
        rpcSocket.receive(recvPkt);

      } while (!byte2string(recvPkt.getData())
          .equals("ok")); // the callId in inBuf is not the expected one
    } catch (InterruptedIOException iioe) {
      // timeout
      iioe.printStackTrace();
      return false;
    } catch (SocketException e0) {
      // TODO Auto-generated catch block
      e0.printStackTrace();
      return false;
    }

    rpcSocket.close();
    return true;
  }
Beispiel #9
0
  /**
   * This is a special method to perform a more efficient packet receive. It should only be used
   * after calling {@link #beginBufferedOps beginBufferedOps() }. beginBufferedOps() initializes a
   * set of buffers used internally that prevent the new allocation of a DatagramPacket and byte
   * array for each send and receive. To use these buffers you must call the bufferedReceive() and
   * bufferedSend() methods instead of send() and receive(). You must also be certain that you don't
   * manipulate the resulting packet in such a way that it interferes with future buffered
   * operations. For example, a TFTPDataPacket received with bufferedReceive() will have a reference
   * to the internal byte buffer. You must finish using this data before calling bufferedReceive()
   * again, or else the data will be overwritten by the the call.
   *
   * <p>
   *
   * @return The TFTPPacket received.
   * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an
   *     InterruptedIOException is thrown on a DatagramSocket timeout, but in practice we find a
   *     SocketException is thrown. You should catch both to be safe.
   * @throws SocketException If a socket timeout occurs. The Java documentation claims an
   *     InterruptedIOException is thrown on a DatagramSocket timeout, but in practice we find a
   *     SocketException is thrown. You should catch both to be safe.
   * @throws IOException If some other I/O error occurs.
   * @throws TFTPPacketException If an invalid TFTP packet is received. *
   */
  public final TFTPPacket bufferedReceive()
      throws IOException, InterruptedIOException, SocketException, TFTPPacketException {
    __receiveDatagram.setData(__receiveBuffer);
    __receiveDatagram.setLength(__receiveBuffer.length);
    _socket_.receive(__receiveDatagram);

    return TFTPPacket.newTFTPPacket(__receiveDatagram);
  }
Beispiel #10
0
  /* Send RTP packet over the network */
  public void send(int length) throws IOException {

    updateSequence();
    upack.setLength(length);
    usock.send(upack);

    if (upts) {
      upts = false;
      buffer[1] -= 0x80;
    }
  }
Beispiel #11
0
  public void run() {
    try {
      byte buf[] = new byte[DNSConstants.MAX_MSG_ABSOLUTE];
      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      while (this._jmDNSImpl.getState() != DNSState.CANCELED) {
        packet.setLength(buf.length);
        this._jmDNSImpl.getSocket().receive(packet);
        if (this._jmDNSImpl.getState() == DNSState.CANCELED) {
          break;
        }
        try {
          if (this._jmDNSImpl.getLocalHost().shouldIgnorePacket(packet)) {
            continue;
          }

          DNSIncoming msg = new DNSIncoming(packet);
          logger.finest("SocketListener.run() JmDNS in:" + msg.print(true));

          this._jmDNSImpl.ioLock();
          try {
            if (msg.isQuery()) {
              if (packet.getPort() != DNSConstants.MDNS_PORT) {
                this._jmDNSImpl.handleQuery(msg, packet.getAddress(), packet.getPort());
              }
              this._jmDNSImpl.handleQuery(msg, this._jmDNSImpl.getGroup(), DNSConstants.MDNS_PORT);
            } else {
              this._jmDNSImpl.handleResponse(msg);
            }
          } finally {
            this._jmDNSImpl.ioUnlock();
          }
        } catch (IOException e) {
          logger.log(Level.WARNING, "run() exception ", e);
        }
      }
    } catch (IOException e) {
      if (this._jmDNSImpl.getState() != DNSState.CANCELED) {
        logger.log(Level.WARNING, "run() exception ", e);
        this._jmDNSImpl.recover();
      }
    }
    // jP: 20010-01-18. Per issue #2933183. If this thread was stopped
    // by closeMulticastSocket, we need to signal the other party via
    // the jmDNS monitor. The other guy will then check to see if this
    // thread has died.
    // Note: This is placed here to avoid locking the IoLock object and
    // 'this' instance together.
    synchronized (this._jmDNSImpl) {
      this._jmDNSImpl.notifyAll();
    }
  }
Beispiel #12
0
  public static SessionTable sessionReadClient(String sessId, int sessVersion, ArrayList<Server> s)
      throws IOException {
    SessionTable session = null;
    DatagramSocket rpcSocket = new DatagramSocket();
    rpcSocket.setSoTimeout(6000); // Timeout after 2 seconds
    String callID = UUID.randomUUID().toString(); // generate unique id for call
    byte[] outBuf = new byte[512];
    // fill outBuf with callId, operationSESSIONREAD, sessionID, sessionVersionNum
    String outStr = callID + "+0+" + sessId + "+" + sessVersion;
    outBuf = string2byte(outStr);
    for (Server e : s) {
      //		InetAddress ip = InetAddress.getByName("127.0.0.1");
      DatagramPacket sendPkt = new DatagramPacket(outBuf, outBuf.length, e.ip, e.port);
      //		System.out.println("ip: "+e.ip.getHostAddress());
      System.out.println("port: " + e.port);
      rpcSocket.send(sendPkt);
      System.out.println("packet sent to server");
    }

    byte[] inBuf = new byte[512];
    DatagramPacket recvPkt = new DatagramPacket(inBuf, inBuf.length);
    String response = "";
    try {
      do {
        recvPkt.setLength(inBuf.length);
        rpcSocket.receive(recvPkt);
        System.out.println("packet received from server");
        response = byte2string(inBuf);
        String[] strs = response.split("[+]");
        session = new SessionTable(sessId, sessVersion);
        session.setVersion(Integer.parseInt(strs[1]));
        session.setMessage(strs[2]);
        session.setExpiration(Timestamp.valueOf(strs[3]));

      } while (response.equals("")
          || !byte2string(recvPkt.getData())
              .split("[+]")[0]
              .equals(callID)); // the callId in inBuf is not the expected one
    } catch (InterruptedIOException iioe) {
      // timeout
      recvPkt = null;
      System.out.println("time out");
    } catch (SocketException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    rpcSocket.close();
    return session;
  }
  public static void ReceiveUDP() {
    try {
      int port = 9040;

      // Create a socket to listen on the port.
      DatagramSocket dsocket = new DatagramSocket(port);

      // Create a buffer to read datagrams into. If a
      // packet is larger than this buffer, the
      // excess will simply be discarded!
      // TODO: what is the best size for this buffer?
      byte[] buffer = new byte[256];

      // Create a packet to receive data into the buffer
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

      // Now loop forever, waiting to receive packets and printing them.
      while (true) {
        // Wait to receive a datagram
        dsocket.receive(packet);

        // Convert the contents to a string, and display them
        String msg = new String(buffer, 0, packet.getLength());

        // assuming that I know the first 12 bytes are for IP
        // and the following 8 bytes are for score
        String IP = msg.substring(0, 13);
        byte[] resource = new byte[8];

        for (int i = 0; i < 8; ++i) {
          resource[i] = buffer[13 + i];
        }

        double score = ByteBuffer.wrap(resource).getDouble();
        NodeManager.Update(IP, score);

        // System.out.println(packet.getAddress().getHostName() + ": "
        //  + msg);

        // Reset the length of the packet before reusing it.
        packet.setLength(buffer.length);
      }
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  /**
   * * This is a method only available within the package for implementing efficient datagram
   * transport by elminating buffering. It takes a datagram as an argument, and a byte buffer in
   * which to store the raw datagram data. Inside the method, the data is set as the datagram's data
   * and the datagram returned.
   *
   * <p>
   *
   * @param datagram The datagram to create.
   * @param data The buffer to store the packet and to use in the datagram.
   * @return The datagram argument. *
   */
  final DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) {
    int fileLength, modeLength;

    fileLength = _filename.length();
    modeLength = _modeBytes[_mode].length;

    data[0] = 0;
    data[1] = (byte) _type;
    System.arraycopy(_filename.getBytes(), 0, data, 2, fileLength);
    data[fileLength + 2] = 0;
    System.arraycopy(_modeBytes[_mode], 0, data, fileLength + 3, modeLength);

    datagram.setAddress(_address);
    datagram.setPort(_port);
    datagram.setData(data);
    datagram.setLength(fileLength + modeLength + 3);

    return datagram;
  }
Beispiel #15
0
 public void run() {
   byte[] buf = new byte[BUF_SIZE];
   DatagramPacket incomingData = new DatagramPacket(buf, buf.length);
   try {
     while (true) {
       sock.receive(incomingData);
       System.out.println(
           "UDP From:"
               + incomingData.getAddress().getHostAddress()
               + ":"
               + incomingData.getPort());
       System.out.println(new String(incomingData.getData(), 0, incomingData.getLength()));
       System.out.flush();
       incomingData.setLength(buf.length);
     }
   } catch (IOException io_ex) {
     io_ex.printStackTrace();
   }
 }
Beispiel #16
0
    public void process(DatagramPacket packet) throws Exception {
      byte[] data = packet.getData();
      int datalen = packet.getLength();
      InetAddress address = packet.getAddress();
      if (datalen <= 0) {
        LOGGER.warn("Empty Packet arrived from {}", packet.getAddress());
        return;
      }
      String message = new String(data, 0, datalen);
      LOGGER.info("server query : [{}] ({}) {}", address, message.length(), message);
      Args args = new Args(message);
      message = (args.argc() == 0) ? "" : (String) remoteCommands.command(args);

      if (message != null) {
        LOGGER.info("server reply : {}", message);
        data = message.getBytes();
        packet.setData(data);
        packet.setLength(data.length);
      }
    }
  public void run() {
    DatagramPacket dataPacket = null;
    // 时间戳
    IPCameraApplication.setT1(System.currentTimeMillis());

    try {
      udpSocket = new DatagramSocket(IPCameraApplication.PHONE_DEFAULT_PORT);
      dataPacket = new DatagramPacket(buffer, IPCameraApplication.MAX_DATA_PACKET_LENGTH);
      dataPacket.setData(data);
      dataPacket.setLength(data.length);
      dataPacket.setPort(IPCameraApplication.DEVICE_DEFAULT_PORT);
      InetAddress broadcastAddr;
      broadcastAddr = InetAddress.getByName("255.255.255.255");
      dataPacket.setAddress(broadcastAddr);
    } catch (Exception e) {
      Log.e(TAG, e.toString());
    }
    //		if(MyApplication.UDP_BROADCAST_START) {
    //			while(true){//能确保在30秒内接收成功就不用循环发送
    try {

      udpSocket.send(dataPacket);
      Log.d(TAG, "成功发送一次UDP广播");
      //					sleep(3000);
    } catch (Exception e) {
      Log.e(TAG, e.toString());
    }

    //			}
    //		}else{
    if (udpSocket != null) {
      udpSocket.close();
    }

    //		}

  }
  /**
   * Listens for incoming datagrams, stores them for reading by the <tt>read</tt> method and
   * notifies the local <tt>transferHandler</tt> that there's data to be read.
   */
  public void run() {
    DatagramPacket p = new DatagramPacket(buffer, 0, PACKET_RECEIVE_BUFFER_LENGTH);

    while (!closed) {
      try {
        // http://code.google.com/p/android/issues/detail?id=24765
        if (OSUtils.IS_ANDROID) p.setLength(PACKET_RECEIVE_BUFFER_LENGTH);

        receivePacket(p);
      } catch (IOException e) {
        ioError = true;
        break;
      }

      /*
       * Do the DatagramPacketFilters accept the received DatagramPacket?
       */
      DatagramPacketFilter[] datagramPacketFilters = getDatagramPacketFilters();
      boolean accept;

      if (!enabled) accept = false;
      else if (datagramPacketFilters == null) accept = true;
      else {
        accept = true;
        for (int i = 0; i < datagramPacketFilters.length; i++) {
          try {
            if (!datagramPacketFilters[i].accept(p)) {
              accept = false;
              break;
            }
          } catch (Throwable t) {
            if (t instanceof ThreadDeath) throw (ThreadDeath) t;
          }
        }
      }

      if (accept) {
        RawPacket pkts[] = createRawPacket(p);

        for (int i = 0; i < pkts.length; i++) {
          RawPacket pkt = pkts[i];

          pkts[i] = null;

          if (pkt != null) {
            if (pkt.isInvalid()) {
              /*
               * Return pkt to the pool because it is invalid and,
               * consequently, will not be made available to
               * reading.
               */
              poolRawPacket(pkt);
            } else {
              RawPacket oldPkt;

              synchronized (pktSyncRoot) {
                oldPkt = this.pkt;
                this.pkt = pkt;
              }
              if (oldPkt != null) {
                /*
                 * Return oldPkt to the pool because it was made
                 * available to reading and it was not read.
                 */
                poolRawPacket(oldPkt);
              }

              if (videoRecorder != null) videoRecorder.recordData(pkt);

              if ((transferHandler != null) && !closed) {
                try {
                  transferHandler.transferData(this);
                } catch (Throwable t) {
                  /*
                   * XXX We cannot allow transferHandler to
                   * kill us.
                   */
                  if (t instanceof ThreadDeath) {
                    throw (ThreadDeath) t;
                  } else {
                    logger.warn("An RTP packet may have not been" + " fully handled.", t);
                  }
                }
              }
            }
          }
        }
        rawPacketArrayPool.offer(pkts);
      }
    }
  }
Beispiel #19
0
 /**
  * * Receives echoed data and returns its length. The data may be divided up among multiple
  * datagrams, requiring multiple calls to receive. Also, the UDP packets will not necessarily
  * arrive in the same order they were sent.
  *
  * <p>
  *
  * @return Length of actual data received.
  * @exception IOException If an error occurs while receiving the data. *
  */
 public int receive(byte[] data, int length) throws IOException {
   __receivePacket.setData(data);
   __receivePacket.setLength(length);
   _socket_.receive(__receivePacket);
   return __receivePacket.getLength();
 }
Beispiel #20
0
  public Vote lookForLeader() throws InterruptedException {
    try {
      self.jmxLeaderElectionBean = new LeaderElectionBean();
      MBeanRegistry.getInstance().register(self.jmxLeaderElectionBean, self.jmxLocalPeerBean);
    } catch (Exception e) {
      LOG.warn("Failed to register with JMX", e);
      self.jmxLeaderElectionBean = null;
    }

    try {
      self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
      // We are going to look for a leader by casting a vote for ourself
      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);
      HashMap<InetSocketAddress, Vote> votes =
          new HashMap<InetSocketAddress, Vote>(self.quorumPeers.size());
      int xid = epochGen.nextInt();
      while (self.running) {
        votes.clear();
        requestBuffer.clear();
        requestBuffer.putInt(xid);
        requestPacket.setLength(4);
        HashSet<Long> heardFrom = new HashSet<Long>();
        for (QuorumServer server : self.quorumPeers.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);
        if (result.winner.id >= 0) {
          self.setCurrentVote(result.vote);
          if (result.winningCount > (self.quorumPeers.size() / 2)) {
            self.setCurrentVote(result.winner);
            s.close();
            Vote current = self.getCurrentVote();
            self.setPeerState(
                (current.id == self.getId()) ? ServerState.LEADING : ServerState.FOLLOWING);
            if (self.getPeerState() == ServerState.FOLLOWING) {
              Thread.sleep(100);
            }
            return current;
          }
        }
        Thread.sleep(1000);
      }
      return null;
    } finally {
      try {
        if (self.jmxLeaderElectionBean != null) {
          MBeanRegistry.getInstance().unregister(self.jmxLeaderElectionBean);
        }
      } catch (Exception e) {
        LOG.warn("Failed to unregister with JMX", e);
      }
      self.jmxLeaderElectionBean = null;
    }
  }
Beispiel #21
0
  private void startListen() {
    while (true) {
      try {
        in_sock.receive(in_packet);
        debugPrint("Received a packet");

        String askString = new String(buf_in.clone());

        if (askString.startsWith(ASK_STRING)) {
          DataInputStream dis =
              new DataInputStream(
                  new ByteArrayInputStream(
                      buf_in, ASK_STRING.length(), buf_in.length - ASK_STRING.length()));
          int type = dis.readInt();

          int index = -1;
          if (type == 2) {
            index = dis.readInt();
          }

          boolean OkResult;
          int responseInt = -1;
          double responseDouble = 0;

          try {
            if (type == 1) {
              responseInt = m_productContainer.count();
              responseDouble = MainClass.avgPrice(m_productContainer);
            } else if (type == 2) {
              Product product = (Product) m_productContainer.getProduct(index);
              if (product == null) {
                responseInt = -1;
                responseDouble = 0;
              } else {
                responseInt = index;
                responseDouble = product.getPrice();
              }
            } else {
              throw new RuntimeException();
            }

            OkResult = true;
          } catch (Exception e) {
            OkResult = false;
          }

          if (OkResult) {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bs);
            dos.writeBytes(RESPONSE_STRING);
            dos.writeInt(type);
            dos.writeInt(responseInt);
            dos.writeDouble(responseDouble);
            buf_out = bs.toByteArray();
            out_packet.setData(buf_out);
            out_packet.setLength(buf_out.length);
            out_packet.setPort(2001);
            out_packet.setAddress(in_packet.getAddress());
            out_sock.send(out_packet);
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #22
0
  /** The listening thread's run method. */
  @Override
  public void run() {
    DatagramPacket packet = null;

    while (this.running) {
      try {
        IceSocketWrapper localSock;

        synchronized (sockLock) {
          if (!running) return;

          localSock = this.sock;
        }

        /*
         * Make sure localSock's receiveBufferSize is taken into
         * account including after it gets changed.
         */
        int receiveBufferSize = 1500;
        /*
        if(localSock.getTCPSocket() != null)
        {
            receiveBufferSize = localSock.getTCPSocket().
                getReceiveBufferSize();
        }
        else if(localSock.getUDPSocket() != null)
        {
            receiveBufferSize = localSock.getUDPSocket().
                getReceiveBufferSize();
        }
        */

        if (packet == null) {
          packet = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize);
        } else {
          byte[] packetData = packet.getData();

          if ((packetData == null) || (packetData.length < receiveBufferSize)) {
            packet.setData(new byte[receiveBufferSize], 0, receiveBufferSize);
          } else {
            /*
             * XXX Tell the packet it is large enough because the
             * socket will not look at the length of the data array
             * property and will just respect the length property.
             */
            packet.setLength(receiveBufferSize);
          }
        }

        localSock.receive(packet);

        // get lost if we are no longer running.
        if (!running) return;

        logger.finest("received datagram");

        RawMessage rawMessage =
            new RawMessage(
                packet.getData(),
                packet.getLength(),
                new TransportAddress(
                    packet.getAddress(), packet.getPort(), listenAddress.getTransport()),
                listenAddress);

        messageQueue.add(rawMessage);
      } catch (SocketException ex) {
        if (running) {
          logger.log(
              Level.WARNING, "Connector died: " + listenAddress + " -> " + remoteAddress, ex);

          stop();
          // Something wrong has happened
          errorHandler.handleFatalError(
              this, "A socket exception was thrown" + " while trying to receive a message.", ex);
        } else {
          // The exception was most probably caused by calling
          // this.stop().
        }
      } catch (ClosedChannelException cce) {
        logger.log(Level.WARNING, "A net access point has gone useless:", cce);

        stop();
        errorHandler.handleFatalError(
            this, "ClosedChannelException occurred while listening" + " for messages!", cce);
      } catch (IOException ex) {
        logger.log(Level.WARNING, "A net access point has gone useless:", ex);

        errorHandler.handleError(ex.getMessage(), ex);
        // do not stop the thread;
      } catch (Throwable ex) {
        logger.log(Level.WARNING, "A net access point has gone useless:", ex);

        stop();
        errorHandler.handleFatalError(
            this, "Unknown error occurred while listening for messages!", ex);
      }
    }
  }
Beispiel #23
0
  @Override
  public void run() {
    // TODO Auto-generated method stub
    while (running) {
      if (isDebug) Log.i(TAG, "5s扫描设备>>>>>>>>>>>>" + Thread.currentThread());
      receive = 50; // 最大接收数量
      isSend = false;
      String recestr = null;
      try {
        listDevices.clear();
        sendSocket = new DatagramSocket();
        sendSocket.setBroadcast(true);
        sendSocket.setSoTimeout(3000);
        sendSocket.send(sendPacket);
        while (receive-- > 0) {
          sendSocket.receive(recePacket);
          recestr = new String(recedata, recePacket.getOffset(), recePacket.getLength());
          if (recestr.startsWith(DISCOVERY_RESP)) {
            Device device = new Device();
            device.setDeviceName(recestr.substring(9));
            device.setDeviceIp(recePacket.getAddress().getHostAddress());
            if (listDevices.indexOf(device) < 0) {
              listDevices.add(device);
              if (device.getDeviceIp().equals("10.8.8.1")) {
                isSend = true;
                if (isDebug) Log.i(TAG, "扫描到10.8.8.1" + listDevices + "|" + Thread.currentThread());
                sendResult();
                break;
              }
            }
          }

          // 每次接收完UDP数据后,重置长度。否则可能会导致下次收到数据包被截断。
          recePacket.setLength(default_bufferSize);
        }
      } catch (SocketTimeoutException e) {
        if (isDebug) Log.i(TAG, "扫描3s超时" + listDevices + "|" + Thread.currentThread());
        if (!isSend) {
          sendResult();
        }
      } catch (SocketException e) {
        receive = 0;
        if (isDebug) Log.i(TAG, "SocketException>>>>>>" + Thread.currentThread());
        if (mScanListener != null) {
          mScanListener.scanException();
        }
      } catch (IOException e) {
        receive = 0;
        if (isDebug) Log.i(TAG, "SocketException>>>>>>" + Thread.currentThread());
        if (mScanListener != null) {
          mScanListener.scanException();
        }
      }
      sendSocket.close();

      if (wipicoVersion >= 2) {
        // 版本2才进行SSID 扫描
        List<ScanResult> listScanResults = WifiAdmin.getInstance(mContext).getScanResults();
        if (listScanResults != null) {
          for (ScanResult bean : listScanResults) {
            if (DeviceUtil.isMatchSSID(DeviceUtil.ssidCorrect(bean.SSID))) {
              listWifiDevices.add(
                  new Device(DeviceUtil.ssidCorrect(bean.SSID), bean.capabilities, null));
            }
          }
        }
        sendWifiResult();
      }

      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #24
0
  public static void main(String[] args) throws IOException {

    long start = System.currentTimeMillis();
    long used = 0;
    long total = 10000000;
    long step = 2000;

    int port = 8080;

    // Create a socket to listen on the port.
    DatagramSocket dsocket = new DatagramSocket(port, InetAddress.getByName("192.168.1.107"));
    // Create a buffer to read datagrams into. If a
    // packet is larger than this buffer, the
    // excess will simply be discarded!
    byte[] buffer = new byte[2048];
    // Create a packet to receive data into the buffer
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    // String[] s = new String[(int)total];

    // Now loop forever, waiting to receive packets and printing them.
    dsocket.setSoTimeout(1000);
    // actually useless
    dsocket.setReceiveBufferSize(3145728);
    System.out.println("dsocket.getReceiveBufferSize():" + dsocket.getReceiveBufferSize());

    while (used < 30000) {
      // Wait to receive a datagram
      try {
        dsocket.receive(packet);
      } catch (Exception e) {
        // continue ;
        used = System.currentTimeMillis() - start;
        continue;
      }

      // Convert the contents to a string, and display them
      String msg = new String(buffer, 0, packet.getLength());
      // s[cnt] = msg;
      // Reset the length of the packet before reusing it.
      packet.setLength(buffer.length);

      cnt++;
      if (cnt % (step) == 0) {
        used = System.currentTimeMillis() - start;
        System.out.println(
            "recive package:" + cnt + " through-put:" + ((double) cnt / (double) used) * 1000);
        System.out.println(msg);
      }

      if (cnt == total) break;
    }

    used = System.currentTimeMillis() - start;
    System.out.print(
        "used time: "
            + used
            + "ms total: "
            + cnt
            + " pkgs through-put:"
            + ((double) cnt / (double) used) * 1000
            + " req/s lost-package:"
            + (total - cnt));
  }