connection.java

来自「j2me 用socket伪装http实现长连接。从而避免频繁的联网提示。支持cm」· Java 代码 · 共 567 行 · 第 1/2 页

JAVA
567
字号
    }
  }

  private void sendSocket(byte[] body) {
    reconnection = false;
    postBody = body;
    while (true) {
      try {
        os.write(genHeader().getBytes());
//        //#debug error
//        System.out.println("header : "+genHeader());
        if (method == METHODPOST && postBody != null) {
          os.write(postBody);
//          String temp = new String(postBody, "UTF-8");
//          //#debug error
//          System.out.println("postBody : "+temp);
        }
        os.flush();
        break;
      } catch (IOException ex) {
        long lstart = System.currentTimeMillis();
        this.connect();
        reconnection = true;
        long lend = System.currentTimeMillis();
        System.out.println("reconnected finish when send" + " " +
                           (lend - lstart) + "ms");
      }
    }
  }

  private void reset() {
    this.iLength = 0;
    this.iResponseCode = 0;
    this.iLineLength = 0;
    iReplyHeaders.clear();
    iReplyHeaderKeys.removeAllElements();
  }

  protected void processReplyHeaders() {
    String value = (String) iReplyHeaders.get(CONTENT_LENGTH.toLowerCase());
    if (value != null) {
      iLength = Long.parseLong(value);
    }
  }

  protected void addHeader(String aKey, String aValue) {
    aKey = aKey.toLowerCase();
    iReplyHeaders.put(aKey, aValue);
    iReplyHeaderKeys.addElement(aKey);
  }

  protected void readHeaders(InputStream aIs) throws IOException {
    int headerCount = 0;
    do {
      if (readLine(aIs) == 0) {
        break;
      }
      int index = 0;
      for (int i = 0; i < iLineLength; i++) {
        char c = iLineBuffer[i];
        if (c != ':') {
          continue;
        }
        index = i;
        break;
      }

      if (index == 0) {
        throw new IOException("Malformed Header");
      }
      if (iLineBuffer[index + 1] != ' ') {
        throw new IOException("Malformed Header");
      }
      String key = new String(iLineBuffer, 0, index);
      StringBuffer value = new StringBuffer();
      for (int i = index + 2; i < iLineLength; i++) {
        value.append(iLineBuffer[i]);
      }

      iLineLength = 0;
      if (readLine(aIs) == 0) {
        addHeader(key, value.toString());
        break;
      } while (iLineBuffer[0] == ' ') {
        ;
      }
      addHeader(key, value.toString());
    } while (true);
  }

  protected int parseStatusCode(char aChars[], int aOffset) throws IOException {
    int value = 0;
    for (int i = 0; i < 3; i++) {
      char digit = aChars[aOffset + i];
      if (digit < '0' || digit > '9') {
        throw new IOException("");
      }
      value *= 10;
      value += Character.digit(digit, 10);
    }

    return value;
  }

  protected void readStatusLine(InputStream aIs) throws IOException {
    readLine(aIs);
    if (iLineLength < MINIMUM_STATUS_LINE_LENGTH) {
      throw new IOException("");
    }
    int current;
    for (current = 0; current < VERSION_LENGTH - 1; current++) {
      if (VERSION[current] != iLineBuffer[current]) {
        throw new IOException("HTTP-Version Mismatch");
      }
    }

    if (iLineBuffer[current] != '0' && iLineBuffer[current] != '1') {
      throw new IOException("HTTP-Version Mismatch");
    }
    current++;
    if (iLineBuffer[current] != ' ') {
      throw new IOException("Malformed Status-Line");
    }
    current++;
    iResponseCode = parseStatusCode(iLineBuffer, current);
    current += 3;
    if (iLineBuffer[current] != ' ') {
      throw new IOException("");
    }
    current++;
    iResponseMessage = new String(iLineBuffer, current,
                                  iLineLength - current);
    iLineLength = 0;
  }

  protected int readLine(InputStream aIs) throws IOException {
    if (iLineLength != 0) {
      return iLineLength;
    }
    if (iLineBuffer == null) {
      iLineBufferLength = DEFAULT_LINE_BUFFER_SIZE;
      iLineBuffer = new char[iLineBufferLength];
    }
    int i = 0;
    do {
      int b = aIs.read();
      if (b == -1) {
        throw new IOException("Unexpected end of stream");
      }
      if (b == 13) {
        b = aIs.read();
        if (b != 10) {
          throw new IOException("");
        }
        break;
      }
      if (i == iLineBufferLength) {
        char oldLineBuffer[] = iLineBuffer;
        int oldLineBufferLength = iLineBufferLength;
        iLineBufferLength += iLineBufferLength;
        iLineBuffer = new char[iLineBufferLength];
        System.arraycopy(oldLineBuffer, 0, iLineBuffer, 0,
                         oldLineBufferLength);
      }
      iLineBuffer[i] = (char) b;
      iLineLength++;
      i++;
    } while (true);
    return iLineLength;
  }

  public byte[] receive(int timeout) {
    if (this.useSocket) {
      return receiveSocket(timeout);
    } else {
      return receiveHttp(timeout);
    }
  }

  private byte[] receiveHttp(int timeout) {
    HttpConnection hc = (HttpConnection) conn;
    int len = 0;
    int totalLen = 0;
    long timeCounter = 0;

    try {
      this.iResponseCode = hc.getResponseCode();
      is = hc.openInputStream();
      this.iLength = hc.getHeaderFieldInt("content-length", 0);
      if (timeout > 0) {
        timeCounter = System.currentTimeMillis();
      } while (true) {
        try {
          buffer = new byte[(int)this.iLength];
          int i = 0;
          while (true) {
            int d = is.read();
            if (d == -1) {
              throw new IOException();
            }
            buffer[i] = (byte) d;
            i++;
            if (i >= buffer.length) {
              break;
            }
          }
          break;
        } catch (IOException ex) {
          long lstart = System.currentTimeMillis();
          this.connect();
          reconnection = true;
          long lend = System.currentTimeMillis();
          System.out.println("reconnected finish when receive" + " " +
                             (lend - lstart) + "ms");
          break;
        }
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    if (this.iResponseCode != 0 && this.iResponseCode != 200 &&
        this.iResponseCode != 206) {
      return new byte[0];
    }
    return buffer;
  }

  public byte[] receiveSocket(int timeout) {

    reset();

    boolean canRead = false;

    long lrtime = 0, lttime = 0, lrcount = 0, ltcount = 0;
    buffer = new byte[0];
    try {
      readStatusLine(is);
      readHeaders(is);
      processReplyHeaders();
      canRead = true;
    } catch (IOException ex2) {
      canRead = false;
      this.connect();
      reconnection = true;
    }

    while (canRead) {
      try {

        buffer = new byte[(int)this.iLength];
        if (this.iLength == 0) {
          break;
        }
        int i = 0;
        while (true) {
          int d = is.read();
          if (d == -1) {
            throw new IOException();
          }
          buffer[i] = (byte) d;
          i++;
          if (i >= buffer.length) {
            break;
          }
        }
        lrcount++;
        break;
      } catch (IOException ex) {
        this.connect();
        reconnection = true;
        break;
      }
    }

    if (this.iResponseCode != 0 && this.iResponseCode != 200 &&
        this.iResponseCode != 206) {
      return new byte[0];
    }
    return buffer;
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?