@Override
  public void run() {
    if (mDownloadManager != null) {
      mDownloadManager.onStartDownload(this);
    }
    mException = null;
    InputStream inputStream = null;
    BufferedWriter bufferedWriter = null;
    try {
      int bufferSize = 8192;
      if (mDownloadRateLimit > 0 && bufferSize > mDownloadRateLimit << 10) {
        bufferSize = mDownloadRateLimit << 10;
      }
      mTargetFile = new File(getTempFilePath());
      URL url = new URL(getTargetURL());
      String host = url.getHost();
      int port = (url.getPort() == -1) ? url.getDefaultPort() : url.getPort();

      mSocket = new Socket();
      mSocket.setReceiveBufferSize(bufferSize);
      mSocket.setSoTimeout(getTimeoutInterval());
      SocketAddress address = new InetSocketAddress(host, port);
      mSocket.connect(address, getTimeoutInterval());

      Log.i(TAG, "socket receive buffer size is: " + mSocket.getReceiveBufferSize());
      bufferedWriter =
          new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF8"));
      String requestStr = "GET " + url.getFile() + " HTTP/1.1\r\n";

      String hostHeader = "Host: " + host + "\r\n";
      String acceptHeader =
          "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
      String charsetHeader = "Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n";
      String languageHeader = "Accept-Language: zh-CN,zh;q=0.8\r\n";
      String keepHeader = "Connection: close\r\n";

      bufferedWriter.write(requestStr);
      bufferedWriter.write(hostHeader);
      bufferedWriter.write(acceptHeader);
      bufferedWriter.write(charsetHeader);
      bufferedWriter.write(languageHeader);
      bufferedWriter.write(keepHeader);
      if (mLoadedByteLength > 0) {
        bufferedWriter.write("Range: bytes=" + mLoadedByteLength + "-\r\n");
      } else {
        guessFileName();
        String folderPath = getFilePath().substring(0, getFilePath().lastIndexOf("/"));
        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
          folder.mkdirs();
        } else {
          deleteFile(getFilePath());
          deleteFile(getTempFilePath());
        }
      }
      bufferedWriter.write("\r\n");
      bufferedWriter.flush();
      inputStream = mSocket.getInputStream();
      Log.i(TAG, inputStream.getClass().getName());
      HttpResponseHeaderParser responseHeader = new HttpResponseHeaderParser();
      String responseHeaderLine = null;
      char readChar = 0;
      StringBuilder headerBuilder = new StringBuilder();
      while ((byte) (readChar = (char) inputStream.read()) != -1) {
        headerBuilder.append(readChar);
        if (readChar == 10) {
          responseHeaderLine = headerBuilder.substring(0, headerBuilder.length() - 2);
          headerBuilder.setLength(0);
          if (responseHeaderLine.length() == 0) {
            break;
          } else {
            responseHeader.addResponseHeaderLine(responseHeaderLine);
            Log.i(TAG, responseHeaderLine);
          }
        }
      }
      Log.i(TAG, "status code: " + responseHeader.getStatusCode());

      if (mTotalByteLength == 0) {
        mTotalByteLength = responseHeader.getContentLength();
      }
      mOutputStream = new FileOutputStream(mTargetFile, true);
      mByteOutput = new ByteArrayOutputStream();
      byte[] buffer = new byte[bufferSize];
      int length = -1;
      mTimeStart = System.currentTimeMillis();
      mDeltaLByteLength = 0;
      mSleepTime = 0;
      while ((length = inputStream.read(buffer)) != -1 && mIsDownloading) {
        Log.i(TAG, "receive data: " + length + " available: " + inputStream.available());
        mByteOutput.write(buffer, 0, length);
        if (mByteOutput.size() >= getMemoryCacheSize() << 10) {
          writeCache();
        }
        limitTheByteRate(length);
      }
      Log.i(TAG, "receive data: " + length + " available: " + inputStream.available());

    } catch (Exception e) {
      mException = e;
    } finally {
      if (mException != null && mIsDownloading && mDownloadManager != null) {
        mDownloadManager.onFailedDownload(this);
      }
      try {
        if (bufferedWriter != null) {
          bufferedWriter.close();
          bufferedWriter = null;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (inputStream != null) {
          inputStream.close();
          inputStream = null;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      stop();
      writeCache();
      try {
        if (mOutputStream != null) {
          mOutputStream.close();
          mOutputStream = null;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (mByteOutput != null) {
          mByteOutput.close();
          mByteOutput = null;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  /** {@inheritDoc} */
  public Object getOption(SocketOption name) throws IOException {
    if (!(name instanceof StandardSocketOption)) {
      throw new IllegalArgumentException("Unsupported option " + name);
    }

    StandardSocketOption stdOpt = (StandardSocketOption) name;
    final Socket socket = channel.socket();
    try {
      switch (stdOpt) {
        case SO_SNDBUF:
          return socket.getSendBufferSize();

        case SO_RCVBUF:
          return socket.getReceiveBufferSize();

        case SO_KEEPALIVE:
          return socket.getKeepAlive();

        case SO_REUSEADDR:
          return socket.getReuseAddress();

        case TCP_NODELAY:
          return socket.getTcpNoDelay();

        default:
          throw new IllegalArgumentException("Unsupported option " + name);
      }
    } catch (SocketException e) {
      if (socket.isClosed()) {
        throw Util.initCause(new ClosedChannelException(), e);
      }
      throw e;
    }
  }
Example #3
0
  public static void printSocketParameters(Socket cl) throws SocketException {

    boolean SO_KEEPALIVE = cl.getKeepAlive();
    boolean TCP_NODELAY = cl.getTcpNoDelay();

    int SO_LINGER = cl.getSoLinger();
    int SO_TIMEOUT = cl.getSoTimeout();

    int SO_RCVBUF = cl.getReceiveBufferSize();
    int SO_SNDBUF = cl.getSendBufferSize();

    int trafficClassVal = cl.getTrafficClass();
    /*
     		0 <= trafficClassVal <= 255
    	IPTOS_LOWCOST (0x02)
    	IPTOS_RELIABILITY (0x04)
     			IPTOS_THROUGHPUT (0x08)
    	IPTOS_LOWDELAY (0x10)

    */

    int remotePort = cl.getPort();
    int localPort = cl.getLocalPort();
    String localIP = getIPstr(cl.getLocalAddress());
    String remoteIP = getIPstr(cl.getInetAddress());

    System.out.println("Socket Paramaters :");
    System.out.println("SO_KEEPAILVE = " + SO_KEEPALIVE + " TCP_NODELAY = " + TCP_NODELAY);
    System.out.println("SO_LINGER = " + SO_LINGER + "  SO_TIMEOUT = " + SO_TIMEOUT);
    System.out.println("SO_RCVBUF = " + SO_RCVBUF + "  SO_SNDBUF = " + SO_SNDBUF);
    System.out.println("Traffic Class = " + trafficClassVal);
    System.out.println("Local Address = " + localIP + ":" + localPort);
    System.out.println("Remote Address = " + remoteIP + ":" + remotePort);
  }
 @Override
 public int getReceiveBufferSize() {
   try {
     return socket.getReceiveBufferSize();
   } catch (SocketException e) {
     throw new ChannelException(e);
   }
 }
Example #5
0
 /**
  * Creates an <code>ObjectReader</code> for a TCP socket
  *
  * @param socket Socket
  */
 public ObjectReader(Socket socket) {
   try {
     this.buffer = new XByteBuffer(socket.getReceiveBufferSize(), true);
   } catch (IOException x) {
     // unable to get buffer size
     log.warn(
         "Unable to retrieve the socket receiver buffer size, setting to default 43800 bytes.");
     this.buffer = new XByteBuffer(43800, true);
   }
 }
 public ClientConnection(
     HazelcastClientInstanceImpl client,
     IOSelector in,
     IOSelector out,
     int connectionId,
     SocketChannelWrapper socketChannelWrapper)
     throws IOException {
   final Socket socket = socketChannelWrapper.socket();
   this.connectionManager = client.getConnectionManager();
   this.serializationService = client.getSerializationService();
   this.lifecycleService = client.getLifecycleService();
   this.socketChannelWrapper = socketChannelWrapper;
   this.connectionId = connectionId;
   this.readHandler = new ClientReadHandler(this, in, socket.getReceiveBufferSize());
   this.writeHandler = new ClientWriteHandler(this, out, socket.getSendBufferSize());
 }
  /** Connects to the filtering server and prepares I/O streams. */
  private void initConnection() throws ReplicatorException {
    try {
      // Connect to filtering server.
      logger.info("Connecting to the filtering server on port " + serverPort);
      InetAddress host = InetAddress.getByName("localhost");
      socket = new Socket(host, serverPort);
      socket.setSoTimeout(timeout * 1000);
      logger.debug("Receive buffer size: " + socket.getReceiveBufferSize());
      logger.info("Connected to " + socket.getRemoteSocketAddress());

      toServer = new PrintWriter(socket.getOutputStream(), true);
      fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
      throw new ReplicatorException("Unable to connect to filtering server: " + e, e);
    } catch (IOException e) {
      throw new ReplicatorException("Unable to connect to filtering server: " + e, e);
    }
  }
  /* Log relevant socket creation details */
  private void recordSocketCreation(SocketDestination dest, Socket socket) throws SocketException {
    int numCreated = created.incrementAndGet();
    logger.debug("Created socket " + numCreated + " for " + dest.getHost() + ":" + dest.getPort());

    // check buffer sizes--you often don't get out what you put in!
    int sendBufferSize = socket.getSendBufferSize();
    int receiveBufferSize = socket.getReceiveBufferSize();
    if (receiveBufferSize != this.socketBufferSize)
      logger.debug(
          "Requested socket receive buffer size was "
              + this.socketBufferSize
              + " bytes but actual size is "
              + receiveBufferSize
              + " bytes.");
    if (sendBufferSize != this.socketBufferSize)
      logger.debug(
          "Requested socket send buffer size was "
              + this.socketBufferSize
              + " bytes but actual size is "
              + sendBufferSize
              + " bytes.");
  }
 @Override
 public int getReceiveBufferSize() throws SocketException {
   return sock.getReceiveBufferSize();
 }
Example #10
0
 public int getReceiveBufferSize() throws SocketException {
   return mSocket.getReceiveBufferSize();
 }
Example #11
0
    void connect(
        String password, final NetworkInterface network_interface, final ServiceAddress addr)
        throws IOException {

      // Creating the socket connection is a privileged operation because it
      // is dynamic (a call stack that ends up here can be from anything).
      // We assume that all objects that call through to this are secured.
      try {
        AccessController.doPrivileged(
            new PrivilegedExceptionAction<Object>() {
              @Override
              public Object run() throws IOException {
                InetAddress iaddr = addr.asInetAddress();

                // IPv6 addresses must have a scope id if they are link local. We
                // assign a network interface to all IPv6 addresses here.

                // If it's an ipv6,
                if (iaddr instanceof Inet6Address) {
                  Inet6Address i6addr = (Inet6Address) iaddr;
                  NetworkInterface current_interface = i6addr.getScopedInterface();
                  // If it has no scope id,
                  if (current_interface == null) {
                    if (network_interface == null) {
                      // If no network interface, then throw an error only if it's a
                      // link local address,
                      if (i6addr.isLinkLocalAddress()) {
                        String err_msg =
                            MessageFormat.format(
                                "Attempting to connect to link local ''{0}'' with no network interface specified.",
                                i6addr);
                        throw new IOException(err_msg);
                      }
                      // IP address is not link local and so does not need a
                      // network scope. Good to go!
                    } else { // network_interface != null
                      // Give the IP address the specified scope,
                      // Make an Inet6Address with the network interface scope,
                      // The must happen for link local IPv6 addresses.
                      iaddr =
                          Inet6Address.getByAddress(null, i6addr.getAddress(), network_interface);
                    }
                  } else {
                    // Otherwise throw an error if we tried to connect on an
                    // interface that's not the same as the interface specified.
                    // Check the scopes are the same,
                    if (network_interface != null && !current_interface.equals(network_interface)) {
                      throw new IOException(
                          "Trying to connect to an interface that's different "
                              + "than the output_net_interface specified.");
                    }
                  }
                }

                s = new Socket(iaddr, addr.getPort());
                return null;
              }
            });
      }
      // Rethrow as IOException
      catch (PrivilegedActionException e) {
        throw (IOException) e.getCause();
      }

      // Set up socket properties,
      s.setSoTimeout(30 * 1000); // 30 second timeout,
      s.setTcpNoDelay(true);
      int cur_send_buf_size = s.getSendBufferSize();
      if (cur_send_buf_size < 256 * 1024) {
        s.setSendBufferSize(256 * 1024);
      }
      int cur_receive_buf_size = s.getReceiveBufferSize();
      if (cur_receive_buf_size < 256 * 1024) {
        s.setReceiveBufferSize(256 * 1024);
      }

      in = new BufferedInputStream(s.getInputStream(), 4000);
      out = new BufferedOutputStream(s.getOutputStream(), 4000);

      DataInputStream din = new DataInputStream(in);
      long rv = din.readLong();

      // Send the password,
      DataOutputStream dout = new DataOutputStream(out);
      dout.writeLong(rv);
      short sz = (short) password.length();
      dout.writeShort(sz);
      for (int i = 0; i < sz; ++i) {
        dout.writeChar(password.charAt(i));
      }
      dout.flush();

      message_dictionary = new HashMap<>(128);
    }