62,614
社区成员
发帖
与我相关
我的任务
分享
//下面是一段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;
}