private void cleanup() {
   running = false;
   try {
     sendOutput.close();
     datagramPacketReceive.setData(new byte[0]);
     datagramPacketSend.setData(new byte[0]);
   } catch (Throwable ignored) {
   }
   stopLatch.countDown();
 }
Exemple #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");
    }
  }
Exemple #3
0
  public void run() throws SocketException {
    DatagramSocket socket = null;
    try {
      socket = new DatagramSocket(53);

      logger.info("Listening on DNS Port(53)");

      int ECHOMAX = 2048;

      DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);

      while (true) {
        try {
          socket.receive(packet);
        } catch (IOException e) {
          e.printStackTrace();
        }
        byte[] data = packet.getData();
        int length = packet.getLength();
        byte[] d = new byte[length];
        System.arraycopy(data, 0, d, 0, length);
        byte[] response = parse(d);

        DatagramPacket re =
            new DatagramPacket(response, response.length, packet.getAddress(), packet.getPort());
        re.setData(response);
        socket.send(re);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #4
0
  public void run() {
    final byte[] receive_buf = new byte[65535];
    DatagramPacket packet = new DatagramPacket(receive_buf, receive_buf.length);
    byte[] data;
    ByteArrayInputStream inp_stream;
    DataInputStream inp = null;
    Message msg;

    while (mcast_sock != null && receiver != null && Thread.currentThread().equals(receiver)) {
      packet.setData(receive_buf, 0, receive_buf.length);
      try {
        mcast_sock.receive(packet);
        data = packet.getData();
        inp_stream = new ExposedByteArrayInputStream(data, 0, data.length);
        inp = new DataInputStream(inp_stream);
        msg = new Message();
        msg.readFrom(inp);
        up(new Event(Event.MSG, msg));
      } catch (SocketException socketEx) {
        break;
      } catch (Throwable ex) {
        log.error("failed receiving packet (from " + packet.getSocketAddress() + ")", ex);
      } finally {
        Util.close(inp);
      }
    }
    if (log.isTraceEnabled()) log.trace("receiver thread terminated");
  }
 /** @see java.net.DatagramSocketImpl#receive(java.net.DatagramPacket) */
 protected void onReceive(DatagramPacket p, SocketBuffer skbuf) throws IOException {
   final IPv4Header ipHdr = (IPv4Header) skbuf.getNetworkLayerHeader();
   final UDPHeader udpHdr = (UDPHeader) skbuf.getTransportLayerHeader();
   p.setData(skbuf.toByteArray(), 0, skbuf.getSize());
   p.setAddress(ipHdr.getSource().toInetAddress());
   p.setPort(udpHdr.getSrcPort());
 }
Exemple #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();
  }
Exemple #7
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);
    }
  }
Exemple #8
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);
  }
  private String lookupFarm() {
    if (Response != null) {

      if (Response.isStillValid()) {

        return Response.getFarmID();
      }

      Response = null;
    }

    try {
      InetAddress CDPServer;
      DatagramSocket Socket;
      CDPQuery Query;
      byte[] Buffer;
      DatagramPacket Packet;

      /* Get the IP address of the CDP servers. */
      CDPServer = InetAddress.getByName(CDPServerName);

      /* Create a UDP socket for the CDP query. */
      Socket = new DatagramSocket();
      Socket.setSoTimeout(CDPTimeout);

      /* Build the CDP query. */
      Query = new CDPQuery(Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION);
      Buffer = Query.getBytes();
      Packet = new DatagramPacket(Buffer, Buffer.length, CDPServer, CDPPort);

      /* Send the query to the CDP server. */
      Socket.send(Packet);

      /* Receive the CDP response. */
      Buffer = new byte[CDPResponse.MaxSize];
      Packet.setData(Buffer);
      Socket.receive(Packet);
      if (Packet.getAddress() != CDPServer || Packet.getPort() != CDPPort)
        throw (new Exception("CDP server address mismatch on response"));

      /* Parse the CDP response. */
      Response = new CDPResponse(Packet.getData());

      /* Return the farmID from the CDP response. */
      return Response.getFarmID();
    } catch (Throwable Excpt) {

      if (Excpt instanceof UnknownHostException) {

      } else {

        Excpt.printStackTrace();
      }

      return "default";
    }
  }
  @Override
  protected void doWriteMessages(MessageBuf<Object> buf) throws Exception {
    DatagramPacket p = (DatagramPacket) buf.poll();
    ByteBuf data = p.data();
    int length = data.readableBytes();
    InetSocketAddress remote = p.remoteAddress();
    if (remote != null) {
      tmpPacket.setSocketAddress(remote);
    }
    if (data.hasArray()) {
      tmpPacket.setData(data.array(), data.arrayOffset() + data.readerIndex(), length);
    } else {
      byte[] tmp = new byte[length];
      data.getBytes(data.readerIndex(), tmp);
      tmpPacket.setData(tmp);
    }

    socket.send(tmpPacket);
  }
 public void run() {
   try {
     byte[] data = str.getBytes();
     DatagramSocket socket = new DatagramSocket(PORT_SEND);
     DatagramPacket packet =
         new DatagramPacket(data, data.length, InetAddress.getByName(IP), PORT_RECEIVE);
     packet.setData(data);
     socket.send(packet);
     socket.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 public void send(JoinMessage joinMessage) {
   if (!running) return;
   final BufferObjectDataOutput out = sendOutput;
   synchronized (sendLock) {
     try {
       out.writeByte(Packet.VERSION);
       out.writeObject(joinMessage);
       datagramPacketSend.setData(out.toByteArray());
       multicastSocket.send(datagramPacketSend);
       out.clear();
     } catch (IOException e) {
       logger.warning("You probably have too long Hazelcast configuration!", e);
     }
   }
 }
Exemple #13
0
  @Override
  protected void send(PacketData data) throws IOException {
    if (hostAddress != null) {
      if (sendPacket == null) {
        sendPacket = new DatagramPacket(data.data, data.dataLength, hostAddress, hostPort);
      } else {
        sendPacket.setData(data.data, 0, data.dataLength);
        sendPacket.setAddress(hostAddress);
        sendPacket.setPort(hostPort);
      }

      socket.send(sendPacket);
    } else {
      Log.w(TAG, "Still awaiting connection from remote host.");
    }
  }
Exemple #14
0
  public static void main(final String[] args) throws Exception {
    //        System.setProperty("java.net.preferIPv4Stack", "true");

    if (2 != args.length && 3 != args.length) {
      System.out.println(
          "Usage: java MulticastSender <multicast address> <number of messages> [interface]");
      return;
    }

    final String address = args[0];

    final long count = Long.parseLong(args[1]);

    final int port = 4445;
    final int serverPort = 4447;

    final byte[] buffer = "This is a test string with sufficient data to send".getBytes("ASCII");

    final InetAddress group = InetAddress.getByName(address);
    MulticastSocket socket;

    if (3 == args.length) {
      final String interfaceAddress = args[2];
      System.out.println("Binding to interface: " + interfaceAddress);
      socket = new MulticastSocket(new InetSocketAddress(interfaceAddress, serverPort));
    } else {
      socket = new MulticastSocket(serverPort);
    }

    final DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);

    final MulticastSender sender = new MulticastSender();
    final Thread t = new Thread(sender);
    t.setDaemon(true);
    t.start();

    for (long i = count; --i != 0; ) {
      packet.setData(buffer);
      socket.send(packet);
      sender.messageCounter++;
    }

    Thread.sleep(1000);

    socket.close();
  }
Exemple #15
0
  // Thread logic
  public void run() {
    while (true) {
      // micData = new byte[microphone.available()];
      lastNumBytesRead = microphone.read(micData, 0, micData.length);

      // dp.setData(micData);
      DatagramPacket dp = new DatagramPacket(micData, Math.min(MAXBUFSIZE, micData.length));

      try {
        // System.out.println("input: " + buf[5]);
        dp.setData(micData);
        dSocket.send(dp);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  /**
   * * 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;
  }
  @Override
  public void run() {
    DatagramSocket socket = null;
    try {

      socket = this.socketProvider.get();
      outputData.reset();
      prependNewline = false;
      writer = new BufferedWriter(new OutputStreamWriter(this.outputData));

      final long epoch = clock.time() / 1000;
      if (this.printVMMetrics) {
        printVmMetrics(epoch);
      }
      printRegularMetrics(epoch);

      // Send UDP data
      writer.flush();

      DatagramPacket packet = this.socketProvider.newPacket(outputData);

      packet.setData(outputData.toByteArray());
      socket.send(packet);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Error writing to Graphite", e);
      } else {
        log.warn("Error writing to Graphite: {}", e.getMessage());
      }
      if (writer != null) {
        try {
          writer.flush();
        } catch (IOException e1) {
          log.error("Error while flushing writer:", e1);
        }
      }
    } finally {
      if (socket != null) {
        socket.close();
      }
      writer = null;
    }
  }
  /**
   * This function simply receives the UDP frame to be sent and send it with
   *
   * <p>the socket and packet created with CreationSocketPacket (). It must be
   *
   * <p>executed in a thread.
   */
  public void EnvoiTrameUDP(String ComandeUDP) {

    try { // INSERTION TRAME
      buffer = ComandeUDP.concat("\r").getBytes("ASCII");

    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    udp_packet.setData(buffer); // Changement de la commande du packet

    try {
      udp_socket.send(udp_packet);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    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 runClient() throws IOException {
    try {
      dataClient = new DatagramSocket();

      dataOut = "1".getBytes();
      dataSent = new DatagramPacket(dataOut, dataOut.length, getAddress(), getPort());
      dataClient.send(dataSent);

      Scanner input = new Scanner(System.in);
      // setSocket(new Socket(getAddress(),getPort()));
      // in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      // out = new PrintWriter(socket.getOutputStream(),true);
      while (true) {
        /* Preparing Input from Server */
        // serverResponse = in.readLine();
        try {
          dataReceived.setData(dataIn);
          dataClient.receive(dataReceived);
          serverResponse = new String(dataReceived.getData());

          if (serverResponse.equals("1")) { // if key for getting client input is called
            /* Outputting to Server */
            clientResponse = input.nextLine(); // Get what the user types.

            dataOut = clientResponse.getBytes();
            dataSent = new DatagramPacket(dataOut, dataOut.length, getAddress(), getPort());
            dataClient.send(dataSent);
            // out.println(clientResponse);
          } else {
            System.out.println(serverResponse);
          }
        } catch (Exception e) {
        }
      }

    } catch (Exception e) {
      /**/
    } finally {
      /* socket.close(); */
    }
  }
  @Override
  protected int doReadMessages(MessageBuf<Object> buf) throws Exception {
    if (readSuspended) {
      try {
        Thread.sleep(SO_TIMEOUT);
      } catch (InterruptedException e) {
        // ignore;
      }
      return 0;
    }

    int packetSize = config().getReceivePacketSize();
    byte[] data = new byte[packetSize];
    tmpPacket.setData(data);
    try {
      socket.receive(tmpPacket);
      InetSocketAddress remoteAddr = (InetSocketAddress) tmpPacket.getSocketAddress();
      if (remoteAddr == null) {
        remoteAddr = remoteAddress();
      }
      buf.add(
          new DatagramPacket(
              Unpooled.wrappedBuffer(data, tmpPacket.getOffset(), tmpPacket.getLength()),
              remoteAddr));

      if (readSuspended) {
        return 0;
      } else {
        return 1;
      }
    } catch (SocketTimeoutException e) {
      // Expected
      return 0;
    } catch (SocketException e) {
      if (!e.getMessage().toLowerCase(Locale.US).contains("socket closed")) {
        throw e;
      }
      return -1;
    }
  }
Exemple #22
0
  public void run() {
    final byte[] receive_buf = new byte[65535];
    DatagramPacket packet = new DatagramPacket(receive_buf, receive_buf.length);
    DataInput inp;

    while (sock != null && receiver != null && Thread.currentThread().equals(receiver)) {
      packet.setData(receive_buf, 0, receive_buf.length);
      try {
        sock.receive(packet);
        inp =
            new ByteArrayDataInputStream(packet.getData(), packet.getOffset(), packet.getLength());
        Message msg = new Message();
        msg.readFrom(inp);
        up(msg);
      } catch (SocketException socketEx) {
        break;
      } catch (Throwable ex) {
        log.error(Util.getMessage("FailedReceivingPacketFrom"), packet.getSocketAddress(), ex);
      }
    }
    if (log.isTraceEnabled()) log.trace("receiver thread terminated");
  }
  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();
    }

    //		}

  }
  private void injectInformation(byte[] information, int offset) {
    int packetLength = packet.getLength();
    int startIndex = packetLength - offset;

    packet.setData(createNewData(information, startIndex));
  }
Exemple #25
0
  /** Method to keep the connection alive with the name server */
  public void run() {
    boolean connected = false;
    int ticket = 0;
    int serial = -1;
    int time = 1000;

    DatagramPacket inPack = new DatagramPacket(new byte[1024], 1024);
    DatagramPacket outPack = new DatagramPacket(new byte[1024], 1024);

    ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
    DataInputStream inData;
    DataOutputStream outData = new DataOutputStream(outBuf);

    while (running) {
      if (!connected) { // Thoust ought Register thine self
        try {
          outBuf.reset();
          outData.writeByte(0);
          outData.writeUTF(userName);
          outData.writeInt(portNum);
          outData.flush();
          outPack.setData(outBuf.toByteArray());
          nameServer.send(outPack);
        } catch (IOException e) {
          System.err.println("LeetActive: " + e);
        }
      } else { // Thoust ought Renew thine self
        try {
          outBuf.reset();
          outData.writeByte(2);
          outData.writeInt(ticket);
          outData.flush();
          outPack.setData(outBuf.toByteArray());
          nameServer.send(outPack);
        } catch (IOException e) {
          System.err.println(e);
        }
      }

      // Now we will receive a packet...
      try {
        nameServer.receive(inPack);
        inData = new DataInputStream(new ByteArrayInputStream(inPack.getData()));

        byte type = inData.readByte();

        if (type == 1) { // Twas a ticket packet
          try {
            ticket = inData.readInt();
            if (ticket > -1) { // Make sure its not evil
              connected = true;
            } else {
              connected = false;
            }
            time = inData.readInt();
          } catch (IOException e) {
            System.err.println(e);
          }
        }

        if (type == 5) { // Twas an update packet
          try {
            int s = inData.readInt();
            if (s > serial) { // Make sure its not old
              serial = s;
              int size = inData.readInt();
              ArrayList newList = new ArrayList(size);

              for (int x = 0; x < size; x++) {
                newList.add(
                    new String(
                        "" + inData.readUTF() + "@" + inData.readUTF() + ":" + inData.readInt()));
              }

              if (!newList.equals(hostList)) {
                hostList = newList;
                updated = true;
              }
            }
          } catch (IOException e) {
            System.err.println(e);
          }
        }
      } catch (SocketTimeoutException e) { // Server hates you
        connected = false;
        System.err.println(e);
      } catch (IOException e) {
        System.err.println(e);
      }

      try { // Take a nap
        sleep(time / 4);
      } catch (InterruptedException e) {
      }
    }
  }
Exemple #26
0
  public void run() {
    DatagramPacket packet;
    byte receive_buf[] = new byte[65535];
    int len;
    byte[] tmp, data;

    // moved out of loop to avoid excessive object creations (bela March 8 2001)
    packet = new DatagramPacket(receive_buf, receive_buf.length);

    while (mcast_receiver != null && mcast_sock != null) {
      try {
        packet.setData(receive_buf, 0, receive_buf.length);
        mcast_sock.receive(packet);
        len = packet.getLength();
        data = packet.getData();
        if (len == 1 && data[0] == 0) {
          if (Trace.debug) {
            Trace.info("UDP.run()", "received dummy packet");
          }
          continue;
        }

        if (len == 4) { // received a diagnostics probe
          if (data[0] == 'd' && data[1] == 'i' && data[2] == 'a' && data[3] == 'g') {
            handleDiagnosticProbe(packet.getAddress(), packet.getPort());
            continue;
          }
        }

        if (Trace.debug) {
          Trace.info(
              "UDP.receive()",
              "received (mcast) "
                  + packet.getLength()
                  + " bytes from "
                  + packet.getAddress()
                  + ":"
                  + packet.getPort()
                  + " (size="
                  + len
                  + " bytes)");
        }
        if (len > receive_buf.length) {
          Trace.error(
              "UDP.run()",
              "size of the received packet ("
                  + len
                  + ") is bigger than "
                  + "allocated buffer ("
                  + receive_buf.length
                  + "): will not be able to handle packet. "
                  + "Use the FRAG protocol and make its frag_size lower than "
                  + receive_buf.length);
        }

        if (Version.compareTo(data) == false) {
          Trace.warn(
              "UDP.run()",
              "packet from "
                  + packet.getAddress()
                  + ":"
                  + packet.getPort()
                  + " has different version ("
                  + Version.printVersionId(data, Version.version_id.length)
                  + ") from ours ("
                  + Version.printVersionId(Version.version_id)
                  + "). This may cause problems");
        }

        if (use_incoming_packet_handler) {
          tmp = new byte[len];
          System.arraycopy(data, 0, tmp, 0, len);
          incoming_queue.add(tmp);
        } else {
          handleIncomingUdpPacket(data);
        }
      } catch (SocketException sock_ex) {
        if (Trace.trace) {
          Trace.info("UDP.run()", "multicast socket is closed, exception=" + sock_ex);
        }
        break;
      } catch (InterruptedIOException io_ex) { // thread was interrupted
        ; // go back to top of loop, where we will terminate loop
      } catch (Throwable ex) {
        Trace.error("UDP.run()", "exception=" + ex + ", stack trace=" + Util.printStackTrace(ex));
        Util.sleep(300); // so we don't get into 100% cpu spinning (should NEVER happen !)
      }
    }
    if (Trace.trace) {
      Trace.info("UDP.run()", "multicast thread terminated");
    }
  }
Exemple #27
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();
 }
    @Override
    public void run() {

      try {
        // Create a packet for sending data
        DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length);

        OutputStream outputStream = null;
        String fileName = "";
        boolean createFile = true;
        int bytesReceived = 0;
        long totalBytesReceived = 0;
        long fileSize = 0;

        socket.receive(receivePacket);

        // Display the client number
        textArea.append("Starting thread for UDP client " + clientNo + " at " + new Date() + '\n');

        textArea.append(
            "The client host name is "
                + receivePacket.getAddress().getHostName()
                + " and port number is "
                + receivePacket.getPort()
                + '\n');

        // Continuously serve the client
        while (true) {
          bytesReceived = receivePacket.getLength();

          if (bytesReceived
              > 0) { // Get the file transmission header from the initial client packet
            String transmitHeader = new String(receivePacket.getData(), 0, bytesReceived);
            // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().;
            String[] header = transmitHeader.split(HEADER_DEL);
            fileSize = Long.parseLong(header[0]);
            fileName = header[1];

            // Send receipt acknowledgment back to the client. Just send back the number of bytes
            // received.
            setSendPacketAddress(sendPacket, receivePacket);
            sendPacket.setData(String.valueOf(bytesReceived).getBytes());
            socket.send(sendPacket);
          }

          while (totalBytesReceived < fileSize) {
            // Wait for client to send bytes
            // socket.setSendBufferSize(BUFFER_SIZE);
            socket.receive(receivePacket);
            bytesReceived = receivePacket.getLength();

            if (totalBytesReceived == 0) {
              if (createFile) { // Get a unique name for the file to be received
                // fileName = getUniqueFileName();
                fileName = textFolder.getText() + fileName;
                outputStream = createFile(fileName);
                createFile = false;
                textArea.append("Receiving file from client.\n");
              }

              // Write bytes to file
              outputStream.write(receivePacket.getData(), 0, bytesReceived);
            } else {
              if (outputStream != null) { // Write bytes to file, if any
                outputStream.write(receivePacket.getData(), 0, bytesReceived);
              }
            }

            // Increment total bytes received
            totalBytesReceived += bytesReceived;

            // Tell the client to send more data. Just send back the number of bytes received.
            sendPacket.setData(String.valueOf(bytesReceived).getBytes());
            socket.send(sendPacket);

            // buffer = new byte[BUFFER_SIZE];
            Arrays.fill(buffer, (byte) 0);

            receivePacket = new DatagramPacket(buffer, buffer.length);
          }

          outputStream.flush();
          outputStream.close();

          textArea.append("Received file successfully. Saved as " + fileName + "\n");

          // Tell the client transmission is complete. Just send back the total number of bytes
          // received.
          sendPacket.setData(String.valueOf(totalBytesReceived).getBytes());
          socket.send(sendPacket);

          // Reset creation flag
          createFile = true;
          totalBytesReceived = 0;

          // Wait for client to send another file
          socket.receive(receivePacket);
        }
      } catch (IOException e) {
        System.err.println(e);
      }
    }
Exemple #29
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();
      }
    }
  }
Exemple #30
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);
      }
    }
  }