gpt4 book ai didi

c# - 将文件从 Java 发送到 C#

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:41 24 4
gpt4 key购买 nike

我想将二进制文件从 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 直到结束。

有什么建议吗?

谢谢

最佳答案

来自 MSDN : "读取操作读取尽可能多的可用数据,直到大小参数指定的字节数。"

这意味着您不一定会获得您请求的那么多数据,您需要检查自己,直到获得您期望的数据为止。

int toRead = (int)length;
int read = 0;
while (toRead > 0)
{
int noChars = networkStream.Read(buffer, read, toRead);
read += noChars;
toRead -= noChars;
}

关于c# - 将文件从 Java 发送到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10129296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com