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();
    }
    
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值