我想将二进制文件从 Java 服务器发送到 C# 客户端。这是我正在使用的代码:
Java服务器:
ServerSocket serverSocket = new ServerSocket(1592);
Socket socket = serverSocket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
File file = new File("img.jpg");
//send file length
out.println(file.length());
//read file to buffer
byte[] buffer = new byte[(int)file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.read(buffer, 0, buffer.length);
//send file
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(buffer);
bos.flush();
Thread.sleep(2000);
C#客户端:
//connect to server
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("127.0.0.1", 1592);
NetworkStream networkStream = tcpClient.GetStream();
StreamReader sr = new StreamReader(networkStream);
//read file length
int length = int.Parse(sr.ReadLine());
Console.WriteLine("File size: {0} bytes", length);
//read bytes to buffer
byte[] buffer = new byte[length];
networkStream.Read(buffer, 0, (int)length);
//write to file
BinaryWriter bWrite = new BinaryWriter(File.Open("C:/img.jpg", FileMode.Create));
bWrite.Write(buffer);
bWrite.Flush();
bWrite.Close();
这段代码似乎只写了文件的前 69696 个字节。从那里它只会写 0 直到结束。
有小费吗?
谢谢