Socket接收大数据时会分成几个包,一次接收不完。用一个buffer来存接收到的包,用count来标示接收数据的大小。
ServerSocket server = new ServerSocket(8002);
Socket socket = server.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream("result.out"));
byte[] buffer = new byte[4096];
int count = 0;
// count 表示接收了的数据大小,如果为0,则说明接收完毕。
while((count = in.read(buffer))>0){
out.write(buffer, 0, count);
}
out.close();
in.close();