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

ihefe ihefe 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

//下面是一段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;
}
...全文
评论 3
收藏 已收藏
分享
返回顶部
ihefe
Java SE 62,620 成员 307,251 内容