socket多线程服务端获取客户端的多个请求

获取客户端的数据格式:length:123\n{string}\n

public class ServerSocketThread extends Thread{
  public static Socket socket = null;
  public  void run() {
    InputStream in = socket.getInputStream();
    byte[] buff = new byte[1024];
    int readLength = -1;
    int length = 0;
    try {
      while (in.read(buff, ++readLength, 1) != -1) {
        if (socket.isClosed()) {
          break;
        }
        if (buff[readLength] == '\n' && length == 0) {
          if (readLength < 8) {
            readLength = -1;
            continue;
          }
          String readString = new String(buff, 0, readLength);//获取length:123
          length = Integer.parseInt(readString.split(":")[1]);
          buff = new byte[length];
          in.read(buff);
          /* 这里开始处理业务并回写 */

          /* 然后准备收下一个包 */
          readLength = -1;
          buff = new byte[1024];
		  length = 0;
        }

      }
      
    }
    catch (BizException ex) {
      //处理捕获异常
      this.interrupt();
    }
    catch (Exception e) {
      //抛出系统异常
      this.interrupt();
    }
    
  }
}

 

你可能感兴趣的:(socket)