Ejemplo n.º 1
0
 private static void readData(String command, DatagramSocket clientSocket, String hostName)
     throws IOException {
   int hostPort = 69, dataSize = 0;
   boolean display = false;
   FileOutputStream myFile = null;
   long startTime = System.currentTimeMillis();
   InetAddress hostAddress = InetAddress.getByName(hostName);
   ByteArrayOutputStream requestBytes = createPacket(command);
   byte[] myResponseData = new byte[516];
   byte[] myRequestData = new byte[516];
   byte[] fileData = new byte[512];
   myRequestData = requestBytes.toByteArray();
   DatagramPacket myDatagramReceivePacket =
       new DatagramPacket(myResponseData, myResponseData.length);
   DatagramPacket myDatagramSendPacket =
       new DatagramPacket(myRequestData, requestBytes.size(), hostAddress, hostPort);
   clientSocket.send(myDatagramSendPacket);
   clientSocket.setSoTimeout(5000);
   try {
     do {
       clientSocket.receive(myDatagramReceivePacket);
       hostPort = myDatagramReceivePacket.getPort();
       byte[] opcode = new byte[2];
       byte[] blockNumber = new byte[2];
       opcode = Arrays.copyOfRange(myDatagramReceivePacket.getData(), 0, 2);
       if (opcode[1] == 5) {
         readError(myDatagramReceivePacket);
       } else if (opcode[1] == 3) {
         clientSocket.setSoTimeout(999999999);
         display = true;
         blockNumber = Arrays.copyOfRange(myDatagramReceivePacket.getData(), 2, 4);
         if (myFile == null) myFile = new FileOutputStream(command);
         fileData =
             Arrays.copyOfRange(
                 myDatagramReceivePacket.getData(), 4, myDatagramReceivePacket.getLength());
         myFile.write(fileData);
         dataSize += myDatagramReceivePacket.getLength();
         ByteArrayOutputStream ackBytes = new ByteArrayOutputStream();
         ackBytes.write(0);
         ackBytes.write(4);
         ackBytes.write(blockNumber);
         for (int i = ackBytes.size(); i < 516; i++) {
           ackBytes.write(0);
         }
         DatagramPacket myDatagramAckSendPacket =
             new DatagramPacket(ackBytes.toByteArray(), ackBytes.size(), hostAddress, hostPort);
         clientSocket.send(myDatagramAckSendPacket);
       }
     } while ((myDatagramReceivePacket.getLength() == 516));
     if (myFile != null) myFile.close();
     if (display) {
       long endTime = System.currentTimeMillis() - startTime;
       System.out.println("Tranferred " + dataSize + " bytes in " + endTime + " milliseconds.");
     }
   } catch (SocketTimeoutException s) {
     System.out.println("Transfer timed out.");
   }
 }
Ejemplo n.º 2
0
 public String receive(int timeout) {
   try {
     socket.setSoTimeout(timeout);
     String received = receive();
     socket.setSoTimeout(0);
     return received;
   } catch (SocketException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 }
Ejemplo n.º 3
0
  private String receiveDataUdp(InetSocketAddress clientAddress) throws IOException, JSONException {
    EmployeeList employees = new EmployeeList();
    DatagramSocket datagramServer = new DatagramSocket(clientAddress);
    byte dataFromServer[] = new byte[2048];
    boolean isTimeExpired = false;
    datagramServer.setSoTimeout((int) SECONDS.toMillis(PROTOCOL_GROUP_TIMEOUT - 5));

    System.out.println(
        "[INFO] -----------------------------------------\n"
            + "[INFO] Collecting information from nodes....");
    while (!isTimeExpired) {
      DatagramPacket datagramPacketacket =
          new DatagramPacket(dataFromServer, dataFromServer.length);
      try {
        datagramServer.receive(datagramPacketacket);
      } catch (SocketTimeoutException e) {
        System.out.println(
            "[WARNING] -----------------------------------------\n"
                + "[WARNING] Waiting time expired...");
        isTimeExpired = true;
        continue;
      }
      String receivedJson = (String) deserialize(datagramPacketacket.getData());
      System.out.println("[INFO] " + "Received employee in JSON: " + receivedJson);
      employees.add(jsonToEmployee(receivedJson));
    }
    datagramServer.close();
    return employeeToXml(employees);
  }
 public DroneSocketClient(String serverAddress, int clientPort, int serverPort, int pingPort)
     throws DroneSocketClientException {
   this.serverAddress = serverAddress;
   this.clientPort = clientPort;
   this.pingPort = pingPort;
   this.serverPort = serverPort;
   try {
     srvAddr = InetAddress.getByName(serverAddress);
   } catch (UnknownHostException e) {
     if (DEBUG) {
       e.printStackTrace();
       Log.d(TAG, "ERROR: UNKNOWN HOST!");
       throw new DroneSocketClientException("");
     }
   }
   try {
     clientSocket = new DatagramSocket(clientPort);
     clientSocket.setSoTimeout(packetTIMEOUT);
   } catch (SocketException e) {
     if (DEBUG) {
       e.printStackTrace();
       Log.d(TAG, "CLIENTSOCKET BIND ERROR!");
       throw new DroneSocketClientException("");
     }
   }
   inData = new byte[1024];
   outData = new byte[1024];
   outPacket = new DatagramPacket(outData, outData.length, srvAddr, serverPort);
   inPacket = new DatagramPacket(inData, inData.length);
 }
Ejemplo n.º 5
0
    public void run() {

      while (!isThreadRunning) {

        byte[] ack_byte = new byte[2];

        DatagramPacket packet_ack = new DatagramPacket(ack_byte, ack_byte.length);
        try {
          socketAck.setSoTimeout(5);
        } catch (SocketException e) {
          e.printStackTrace();
        }
        try {
          socketAck.receive(packet_ack);
        } catch (IOException e) {
          e.printStackTrace();
        }
        byte[] ackData = packet_ack.getData();
        int packet_ack_num = getAckPaket(ackData);
        num_acked = Math.max(num_acked, packet_ack_num);
        Thread.yield();
      }

      socketAck.close();
    }
Ejemplo n.º 6
0
  public int synackLink(SynAck synPack) {
    /* 请求建立连接 */
    PacketManager mag =
        new PacketManager(Values.HEAD, Values.SYN, 0, Values.SYNACKLEN, null, synPack);
    DatagramPacket sendPacket =
        new DatagramPacket(
            mag.getBuf(), mag.getBuf().length, Values.SERV_ADDRESS, Values.SERV_PORT);
    try {
      socket.send(sendPacket);
      Log.d(
          "johnchain",
          "Commander send SYN to server bytes = "
              + sendPacket.getLength()
              + "|\n"
              + Utils.stringSynAck(synPack));
    } catch (IOException e) {
      Log.e("johnchain", "Commander send SYN failed, transmition aborted");
      return Values.RST_ERROR;
    }

    try {
      socket.setSoTimeout(Values.SOCKET_TIMEOUT * 2);
    } catch (SocketException e1) {
      Log.e("johnchain", "Commander set timeout failed");
    }

    MyMessage myMsg = waitReply(Values.SYN_ACK, sendPacket);
    if (myMsg != null) return Values.RST_OK;
    else return Values.RST_TIMEOUT;
  }
Ejemplo n.º 7
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;
  }
Ejemplo n.º 8
0
  public static List<Usr> getList() throws IOException {
    byte[] host_ip = InetAddress.getLocalHost().getAddress();
    DatagramSocket serverSocket = new DatagramSocket(UDP_PORT);
    byte[] buf = BROADCAST_MSG.getBytes();
    InetAddress address = InetAddress.getByName(ALL_IP);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, UDP_PORT);
    serverSocket.send(packet);
    serverSocket.setSoTimeout(SOCKET_TIMEOUT); // set the timeout in millisecounds.

    ArrayList<Usr> out = new ArrayList<Usr>();
    while (true) {
      try {
        byte[] rcv = new byte[32];
        packet = new DatagramPacket(rcv, rcv.length);
        serverSocket.receive(packet);
        byte[] ip = packet.getAddress().getAddress();
        if (Arrays.equals(ip, host_ip)) continue;
        Usr usr = new Usr(packet.getData());
        out.add(usr);
      } catch (SocketTimeoutException e) {
        break;
      }
    }

    serverSocket.close();
    return out;
  }
 public void receiveMessage(byte[] buffer) throws Exception {
   DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
   synchronized (m_Socket) {
     m_Socket.setSoTimeout(m_Timeout);
     m_Socket.receive(packet);
   }
 }
Ejemplo n.º 10
0
  public void run() {
    try {
      DatagramSocket socket = new DatagramSocket();
      socket.setSoTimeout(Const.SoTimeout);
      slpUdpHandler udp = new slpUdpHandler(socket);
      slpMsgComposer composer = new slpMsgComposer();
      slpMsgParser parser = new slpMsgParser();
      uaAction uac = new uaAction(uaf);

      while (running) {
        while (!tryDiscovery) Thread.sleep(Const.daDiscover_interval);
        // System.out.println( "Discovery via findDA thread");
        uaf.clearDA();
        byte[] mesg =
            composer.SrvRqst(xid, Const.mcast_flag, "en", "", Const.DAAdvert_Rqst, "", "", "");
        String ret = udp.send(mesg, Const.mcast_addr, Const.port);
        if (ret != null) uaf.append(ret);
        tryDiscovery = false;

        while (true) { // try to collect all replies from DAs
          byte[] buf = udp.receive();
          if (buf == null) break; // TimeOut, no more reply
          parser.Header(buf);
          uac.action(parser, buf, Const.header_len);
        }
      }
    } catch (Exception e) {
      if (ServiceLocationManager.displayMSLPTrace) e.printStackTrace();
    }
  }
  /** Initializes the query system by binding it to a port */
  private boolean initQuerySystem() {
    try {
      querySocket = new DatagramSocket(queryPort, InetAddress.getByName(serverHostname));
      registerSocket(querySocket);
      querySocket.setSoTimeout(500);
      return true;
    } catch (SocketException var2) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Socket): "
              + var2.getMessage());
    } catch (UnknownHostException var3) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Unknown Host): "
              + var3.getMessage());
    } catch (Exception var4) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (E): "
              + var4.getMessage());
    }

    return false;
  }
Ejemplo n.º 12
0
    public void run() {
      // Counter to wait for timeout 5 times
      int counter = 5;

      while (running) {
        try {
          byte[] buf = new byte[32];
          packet = new DatagramPacket(buf, buf.length);
          socket.setSoTimeout(1000);

          // Wait for a message
          socket.receive(packet);

          // Clean the string (remove all the null characters)
          String message = new String(packet.getData());
          int endoftext = message.indexOf("\0");
          if (endoftext != -1) message = message.substring(0, endoftext);

          // If the message is different from the one sent
          if (!message.equals("requestIP")) {
            // Broadcast an intent with the message
            Intent answer = new Intent(Constants.UDP_ANSWER);
            answer.putExtra("message", message);
            sendBroadcast(answer);
          }
        } catch (SocketTimeoutException e) {
          // If the socket timed out, decrement the counter
          counter--;
          if (counter == 0) cancel();
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
Ejemplo n.º 13
0
  /*
   * Connect a UDP socket, disconnect it, then send and recv on it.
   * It will fail on Linux if we don't silently bind(2) again at the
   * end of DatagramSocket.disconnect().
   */
  private static void testConnectedUDP(InetAddress addr) throws Exception {
    try {
      DatagramSocket s = new DatagramSocket(0, addr);
      DatagramSocket ss = new DatagramSocket(0, addr);
      System.out.print("\tconnect...");
      s.connect(ss.getLocalAddress(), ss.getLocalPort());
      System.out.print("disconnect...");
      s.disconnect();

      byte[] data = {0, 1, 2};
      DatagramPacket p =
          new DatagramPacket(data, data.length, s.getLocalAddress(), s.getLocalPort());
      s.setSoTimeout(10000);
      System.out.print("send...");
      s.send(p);
      System.out.print("recv...");
      s.receive(p);
      System.out.println("OK");

      ss.close();
      s.close();
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
  public MSSqlServerInfo(String host) throws SQLException {
    try {
      InetAddress addr = InetAddress.getByName(host);
      DatagramSocket socket = new DatagramSocket();
      byte[] msg = new byte[] {0x02};
      DatagramPacket p = new DatagramPacket(msg, msg.length, addr, 1434);

      socket.send(p);

      byte[] buf = new byte[4096];

      p = new DatagramPacket(buf, buf.length);
      socket.setSoTimeout(m_timeout);

      for (int i = 0; i < m_numRetries; i++) {
        try {
          socket.receive(p);
          String infoString = extractString(buf, p.getLength());
          m_serverInfoStrings = split(infoString, ';');

          return;
        } catch (InterruptedIOException toEx) {
        }
      }
    } catch (Exception e) {
      // Ignore...
    }

    throw new SQLException(Messages.get("error.msinfo.badinfo", host), "HY000");
  }
Ejemplo n.º 15
0
 /**
  * Sets the timeout for the UDP socket (in milliseconds). It is mainly used in the receive()
  * function.
  *
  * @param timeout - timeout in milliseconds.
  */
 public void setTimeout(int timeout) {
   try {
     if (socket != null) socket.setSoTimeout(timeout);
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 16
0
  private void getAndSendInitialInfo() {
    byte[] idBuf = new byte[4];
    ByteBuffer buf = ByteBuffer.wrap(idBuf);
    buf.putInt(userid);
    DatagramPacket idPacket = new DatagramPacket(idBuf, idBuf.length);

    byte[] serverAckBuf = new byte[1];
    DatagramPacket serverAckPacket = new DatagramPacket(serverAckBuf, serverAckBuf.length);
    boolean receivedAck = false;
    while (!receivedAck) {
      try {
        ds.setSoTimeout(REG_TIMEOUT);
        System.out.println("CLIENT " + userid + ": attempting to register");
        ds.send(idPacket);
        ds.receive(serverAckPacket);
        receivedAck = true;
        byte indicator = serverAckBuf[0];
        System.out.println("CLIENT " + userid + ": received ack: " + indicator);
        if (indicator == 0 || indicator == 1) {
          team = indicator;
        } else {
          // server error, must exit
          throw new RuntimeException(
              "Server responded with code: " + indicator + ", will not start.");
        }
      } catch (SocketTimeoutException e) {
        continue;
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.println("CLIENT:" + userid + " Done registering.");
    // throw new UnsupportedOperationException();
  }
Ejemplo n.º 17
0
  public PingResult ping(ScanningSubject subject, int count) throws IOException {
    PingResult result = new PingResult(subject.getAddress());

    DatagramSocket socket = sockets.bind(new DatagramSocket());
    socket.setSoTimeout(timeout);
    socket.connect(subject.getAddress(), PROBE_UDP_PORT);

    for (int i = 0; i < count && !Thread.currentThread().isInterrupted(); i++) {
      long startTime = System.currentTimeMillis();
      byte[] payload = new byte[8];
      ByteBuffer.wrap(payload).putLong(startTime);
      DatagramPacket packet = new DatagramPacket(payload, payload.length);
      try {
        socket.send(packet);
        socket.receive(packet);
      } catch (PortUnreachableException e) {
        result.addReply(System.currentTimeMillis() - startTime);
      } catch (SocketTimeoutException ignore) {
      } catch (NoRouteToHostException e) {
        // this means that the host is down
        break;
      } catch (SocketException e) {
        if (e.getMessage().contains(/*No*/ "route to host")) {
          // sometimes 'No route to host' also gets here...
          break;
        }
      } catch (IOException e) {
        LOG.log(FINER, subject.toString(), e);
      }
    }
    return result;
  }
Ejemplo n.º 18
0
  @Override
  public void run() {
    try {
      destination = new InetSocketAddress(address, port);
      DatagramSocket socket = new DatagramSocket(port);
      socket.setSoTimeout(1);
      byte[] recieved = new byte[6];
      DatagramPacket recieved_pkt = new DatagramPacket(recieved, recieved.length);
      DatagramPacket sendPacket =
          new DatagramPacket(sendBuffer.array(), sendBuffer.capacity(), destination);

      while (running) {
        time = System.currentTimeMillis();
        socket.setSoTimeout(Math.max(rtt, 1));
        prepSendBuffer();
        socket.send(sendPacket);
        packetTimes[localSequence % 32] = time;
        localSequence++;
        changed = false;
        nextSendTime = time + MAX_REFRESH_WAIT;
        while (running && !(changed || time > nextSendTime))
          try {
            // Retrieve the echoed sequence number
            socket.receive(recieved_pkt);
            buffer = ByteBuffer.wrap(recieved_pkt.getData());
            buffer.getInt();
            int testShort = unsingnedShortToInt(buffer.getShort());
            rtt = (int) (time - packetTimes[testShort % 32]);
            ControlView.refresh = (ControlView.refresh + rtt) / 2;
            // Set time-out to the last ping
          } catch (IOException e) {
          }
      }
      // Killing thread/app
      // Send a zero sequence, so if we connect again to the server it has
      // a reset counter
      localSequence = 0;
      prepSendBuffer();
      socket.send(sendPacket);
      socket.close();
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 19
0
  @Override
  public void run() {

    DatagramSocket socket;
    int clientListnport = Constants.UDPPort;

    try {
      // Keep a socket open to listen to all the UDP trafic that is
      // destined for this port
      socket = new DatagramSocket(clientListnport, (Inet4Address) InetAddress.getByName("0.0.0.0"));
      socket.setBroadcast(true);
      socket.setSoTimeout(10000);

      while (WifiReceiver.isWifi) {
        System.out.println(">>>Ready to receive broadcast packets!");

        // Receive a packet
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        try {
          socket.receive(packet);

          // Packet received
          System.out.println(
              ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
          // See if the packet holds the right command (message)
          String message = new String(packet.getData()).trim();
          if (message.equals(Constants.serverDiscoverString)) {
            byte[] sendData = Constants.clientReplyString.getBytes();
            // Send a response

            if (!WifiUtils.getipAddress()
                .equalsIgnoreCase(packet.getAddress().getHostAddress().toString())) {
              DatagramPacket sendPacket =
                  new DatagramPacket(
                      sendData, sendData.length, packet.getAddress(), packet.getPort());
              socket.send(sendPacket);

              System.out.println(">>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
            }
          } else if (message.equals(Constants.serverFileSending)) {
            System.out.println("sending reply to recive handshake");
            byte[] sendData = Constants.clientFileReceive.getBytes();
            DatagramPacket sendPacket =
                new DatagramPacket(
                    sendData, sendData.length, packet.getAddress(), packet.getPort());
            socket.send(sendPacket);
            Log.d(loggerTag, "handshaking is done");
            FileReceiver.waitConnection();
          }
        } catch (SocketTimeoutException e) {
          // no need of doing anything
        }
      }
      System.out.println("CLientListener : Listener is stoped");
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
Ejemplo n.º 20
0
  public static void main(String args[]) throws Exception {

    String serverHostname = args[0];
    int portNumber = Integer.parseInt(args[1]);

    try {
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

      DatagramSocket clientSocket = new DatagramSocket();

      InetAddress IPAddress = InetAddress.getByName(serverHostname);
      System.out.println("Attempting to connect to " + IPAddress + ") via UDP port " + portNumber);
      System.out.println("Enter \"Quit\" to exit program");

      while (true) {
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        System.out.print("Enter Message: ");
        String sentence = inFromUser.readLine();

        if (sentence.equals("Quit")) break;

        sendData = sentence.getBytes();

        System.out.println("Sending data to " + sendData.length + " bytes to server.");
        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, portNumber);

        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        System.out.println("Waiting for return packet");
        clientSocket.setSoTimeout(10000);

        try {
          clientSocket.receive(receivePacket);
          String modifiedSentence = new String(receivePacket.getData());

          InetAddress returnIPAddress = receivePacket.getAddress();

          int port = receivePacket.getPort();

          System.out.println("From server at: " + returnIPAddress + ":" + port);
          System.out.println("Message: " + modifiedSentence);
        } catch (SocketTimeoutException ste) {
          System.out.println("Timeout Occurred: Packet assumed lost");
        }
        System.out.print("\n");
      }

      clientSocket.close();
    } catch (UnknownHostException ex) {
      System.err.println(ex);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
Ejemplo n.º 21
0
    public NBResolver(String address) throws SocketException, UnknownHostException {
      super("NBResolver");

      mAddress = InetAddress.getByName(address);
      mSocket = new DatagramSocket();

      mSocket.setSoTimeout(200);
    }
Ejemplo n.º 22
0
  /**
   * ReadAndWriteData
   *
   * <p>Handles sending an OP_ACK packet and receiving a data packet.
   *
   * @param sendSocket
   * @param sendAck OP_ACK packet to be sent
   * @param block block number it is expecting
   * @return data packet or null is connection timeout
   */
  private DatagramPacket ReadAndWriteData(
      DatagramSocket sendSocket, DatagramPacket sendAck, short block) {
    int retryCount = 0;
    byte[] rec = new byte[BUFSIZE];
    DatagramPacket receiver = new DatagramPacket(rec, rec.length);

    while (true) {
      if (retryCount >= 6) {
        System.err.println("Timed out. Closing connection.");
        return null;
      }
      try {
        System.out.println("sending ack for block: " + block);
        sendSocket.send(sendAck);
        sendSocket.setSoTimeout(((int) Math.pow(2, retryCount++)) * 1000);
        sendSocket.receive(receiver);

        short blockNum = getData(receiver);
        System.out.println(blockNum + " " + block);
        if (blockNum == block) {
          return receiver;
        } else if (blockNum == -1) {
          return null;
        } else {
          System.out.println("Duplicate.");
          retryCount = 0;
          throw new SocketTimeoutException();
        }
      } catch (SocketTimeoutException e) {
        System.out.println("Timeout.");
        try {
          sendSocket.send(sendAck);
        } catch (IOException e1) {
          System.err.println("Error sending...");
        }
      } catch (IOException e) {
        System.err.println("IO Error.");
      } finally {
        try {
          sendSocket.setSoTimeout(0);
        } catch (SocketException e) {
          System.err.println("Error resetting Timeout.");
        }
      }
    }
  } // ReadAndWriteData
 protected void setSocketAttributes(DatagramSocket socket) throws SocketException {
   if (this.getSoTimeout() >= 0) {
     socket.setSoTimeout(this.getSoTimeout());
   }
   if (this.getSoSendBufferSize() > 0) {
     socket.setSendBufferSize(this.getSoSendBufferSize());
   }
 }
Ejemplo n.º 24
0
  /**
   * WriteAndReadAck
   *
   * <p>Handles sending a data packet and receiving an ack packet.
   *
   * @param sendSocket
   * @param sender
   * @param blockNum
   * @return true if successful OP_ACK. false if connection timeout.
   */
  private boolean WriteAndReadAck(
      DatagramSocket sendSocket, DatagramPacket sender, short blockNum) {
    int retryCount = 0;
    byte[] rec = new byte[BUFSIZE];
    DatagramPacket receiver = new DatagramPacket(rec, rec.length);

    while (true) {
      if (retryCount >= 6) {
        System.err.println("Timed out. Closing connection.");
        return false;
      }
      try {
        sendSocket.send(sender);
        System.out.println("Sent.");
        sendSocket.setSoTimeout(((int) Math.pow(2, retryCount++)) * 1000);
        sendSocket.receive(receiver);

        /* _______________ Dissect Datagram and Test _______________ */
        short ack = getAck(receiver);
        //	            System.out.println("Ack received: " + ack);
        if (ack == blockNum) {
          //	            	System.out.println("Received correct OP_ACK");
          return true;
        } else if (ack == -1) {
          return false;
        } else {
          //	            	System.out.println("Ignore. Wrong ack.");
          retryCount = 0;
          throw new SocketTimeoutException();
        }
        /* ^^^^^^^^^^^^^^^ Dissect Datagram and Test ^^^^^^^^^^^^^^^ */

      } catch (SocketTimeoutException e) {
        System.out.println("Timeout. Resending.");
      } catch (IOException e) {
        System.err.println("IO Error. Resending.");
      } finally {
        try {
          sendSocket.setSoTimeout(0);
        } catch (SocketException e) {
          System.err.println("Error resetting Timeout.");
        }
      }
    }
  } // WriteAndReadAck
Ejemplo n.º 25
0
 public RequestReceiver(int port) throws IOException {
   UDPserverSocket = new DatagramSocket(port);
   System.out.println(
       "UDP Request Receiver Running on "
           + UDPserverSocket.getInetAddress()
           + ":"
           + UDPserverSocket.getLocalPort());
   UDPserverSocket.setSoTimeout(0);
 }
  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";
    }
  }
Ejemplo n.º 27
0
  /**
   * Sets the timeout in milliseconds for this <tt>UDPSlaveTerminal</tt>.
   *
   * @return the timeout as <tt>int</tt>.
   *     <p>public int getTimeout() { return m_Timeout; }//getTimeout
   *     <p>/** Sets the timeout for this <tt>UDPSlaveTerminal</tt>.
   * @param timeout the timeout as <tt>int</tt>.
   */
  public void setTimeout(int timeout) {
    m_Timeout = timeout;

    try {
      m_Socket.setSoTimeout(m_Timeout);
    } catch (IOException ex) {
      ex.printStackTrace(); // handle? }
    }
  }
Ejemplo n.º 28
0
 private synchronized DatagramSocket ensureSocket() throws SocketException {
   DatagramSocket s = socket;
   if (s == null) {
     s = new DatagramSocket(udpAddress.getPort());
     s.setSoTimeout(socketTimeout);
     this.socket = s;
   }
   return s;
 }
Ejemplo n.º 29
0
 /**
  * Sets the socket timeout in milliseconds.
  *
  * @param socketTimeout the socket timeout for incoming messages in milliseconds. A timeout of
  *     zero is interpreted as an infinite timeout.
  */
 public void setSocketTimeout(int socketTimeout) {
   this.socketTimeout = socketTimeout;
   if (socket != null) {
     try {
       socket.setSoTimeout(socketTimeout);
     } catch (SocketException ex) {
       throw new RuntimeException(ex);
     }
   }
 }
Ejemplo n.º 30
0
  @Override
  protected void open() throws IOException {
    Log.d(TAG, "Opening udp connection.");

    socket = (serverPort == -1) ? new DatagramSocket() : new DatagramSocket(serverPort);

    socket.setBroadcast(true);
    socket.setReuseAddress(true);
    socket.setSoTimeout(readTimeout);
  }