socket断续字节初探



/**
 * 服务端以DataInputStream等待字节全部写入,阻塞时间受 SoTimeout  (Socket operation Timeout)
 */
public class SocketServer {
public static void main(String[] args) throws Exception {

  ServerSocket server = new ServerSocket(3216);
  Socket socket = server.accept();
  
  System.out.println("Socket communication build");
  
  DataInputStream  ois =  new DataInputStream(socket.getInputStream());
  int len1 = ois.readInt();
  int len2 = ois.readInt();
  System.out.println("len1 + len2="+ (len1 + len2));
  socket.setSoTimeout(1000);//timeout设定影响socket的阻塞
  
  byte[] data = new byte[len1+len2];
  
  //plan1 全读等待
  ois.readFully(data);  
  
  //plan2 直接read,读不全
//   ois.read(data);


  
  String str1 = new String(data, 0, len1);
  String str2 = new String(data, len1, len2);
  
  System.out.println(str1);
  System.out.println(str2);
  
  System.out.println(Arrays.toString(data));
  server.close();
}

}


public class SocketClient {
public static void main(String[] args) throws Exception, IOException {
Socket socket = new Socket("127.0.0.1", 3216);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
byte[] str1 = "写信告诉我,今夜的海什么颜色".getBytes();
byte[] str2 = "夜夜陪着你的海,心情又如何".getBytes();
dos.writeInt(str1.length);
dos.writeInt(str2.length);
dos.write(str1);

TimeUnit.SECONDS.sleep(10);
dos.write(str2);
dos.flush();

dos.close();
socket.close();
}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值