socket编程,输入流怎么放入缓冲区?

ihefe 2014-09-28 02:58:16

//下面是一段server端的代码;
//socket协议定义了前4字节是数据包长度;
//如果接收几M的数据包 ,byte[] bufBody不能一次性读出;
//请问如何把输入流全部(1个请求协议包)放到缓冲区,在一次性读出byte[] bufBody?
// implements Runnable
public void run() {
try {
InputStream input = connectedSocket.getInputStream();
//OutputStream output = connectedSocket.getOutputStream();
if (input != null) {
byte[] bufHead = new byte[4];
input.read(bufHead);
int maxLenth = toInt(bufHead);
byte[] bufBody = new byte[maxLenth];
input.read(bufBody);
System.out.println("包长度:"+bufBody.length);
}
} catch (IOException e) {
try {
if (connectedSocket != null) {
connectedSocket.close(); // 关闭套接字
}
} catch (IOException ex) {
e.printStackTrace();
}
System.out.println("异常断开连接:" + e.getMessage());
} finally {
try {
if (connectedSocket != null) {
System.out.println("断开连接");
connectedSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}// end of run
public static int toInt(byte[] bRefArr) {
int iOutcome = 0;
byte bLoop;

for (int i = 0; i < bRefArr.length; i++) {
bLoop = bRefArr[i];
iOutcome += (bLoop & 0xFF) << (8 * (3 - i));
}
return iOutcome;
}
...全文
211 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ihefe 2014-09-28
  • 打赏
  • 举报
回复
引用 1 楼 bayougeng 的回复:
既然是多线程,如果我是你,我就用piped stream。 如果你一定要像现在这么做,那就用ByteArrayOutputStream。读到的数据依次写进去,然后用toByteArray() 方法拿到整个的数组。 我理解对了么?
piped stream 谢谢提了这个建议。 ByteArrayOutputStream 是个好方式。 我目前实现的方式是: 获取的数据流(curr)都被maxLength减掉, 得到剩下的长度: int remain=(max-curr);//剩下多少没接收完成 byte[] bufBody = new byte[remain]; input.read(bufBody);//继续取剩下的数据流,直到完成。 方法可能不好,结帖。
lsongiu86 2014-09-28
  • 打赏
  • 举报
回复
没问题啊这样写
bayougeng 2014-09-28
  • 打赏
  • 举报
回复
既然是多线程,如果我是你,我就用piped stream。 如果你一定要像现在这么做,那就用ByteArrayOutputStream。读到的数据依次写进去,然后用toByteArray() 方法拿到整个的数组。 我理解对了么?

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧