Socket读取数据问题


如图,读取数据的时候不完整,请求支援,谢谢

PS:读取的数据结尾包括\r\n换行符

InputStream inputStream = socket.getInputStream();

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024 * 10];
int length;
while ((length = inputStream.read(buffer)) != -1) {
	byteArrayOutputStream.write(buffer, 0, length);
}

inputStream.close();

byte[] data = byteArrayOutputStream.toByteArray();

String value = new String(data, StandardCharsets.UTF_8);

System.out.println(value);

读取流的时候。read(byte[] in) 方法会返回读取到的字节数。这个数据很关键,底层IO并不能保证一次性把byte[] 装满,可能要读取多次,所以需要循环不断的读取直到读取到了末尾,而每次读取,都会返回 读取到了多少 字节,于是,你必须要从这个 byte[] 里面去获取到本地读取的有效数据。

我给你写一个socket传输文件的demo

没有异常,可以完整的读取到文件数据

服务端

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Server {
	public static void main(String[] args) throws IOException {
		try(ServerSocket serverSocket = new ServerSocket()){
			serverSocket.bind(new InetSocketAddress("0.0.0.0", 1024));
			byte[] data = Files.readAllBytes(Paths.get("D://huge.json"));  // 换成本地磁盘的任意文本文件(utf-8编码)
			while (true) {
				try(Socket socket = serverSocket.accept()){
					OutputStream outputStream = socket.getOutputStream();
					outputStream.write(data);
					outputStream.flush();
					socket.shutdownOutput();
					socket.close();
				}
			}
		}
	}
}

客户端

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try(Socket socket = new Socket("127.0.0.1", 1024)){
			InputStream inputStream = socket.getInputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = inputStream.read(buffer)) != -1) {
				byteArrayOutputStream.write(buffer, 0, length);
			}
			byte[] data = byteArrayOutputStream.toByteArray();
			String value = new String(data, StandardCharsets.UTF_8);
			System.out.println(value);
			socket.shutdownInput();
			socket.close();
		}
	}
}