从Java发送文件到C# [英] Send a file from Java to C#
本文介绍了从Java发送文件到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从Java服务器发送一个二进制文件到C#的客户端。这里的code我使用的是:
I want to send a binary file from a Java server to a C# client. Here's the code I'm using:
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();
这code似乎只写第69696字节的文件。从那里,它只会写0,直到结束。
This code only seems to write the first 69696 bytes of the file. From there it will only write 0 until the end.
任何提示?
感谢
推荐答案
从的 MSDN :因为是可用的,直到由大小参数指定的字节数读操作读取尽可能多的数据
From MSDN: "Read operation reads as much data as is available, up to the number of bytes specified by the size parameter."
这意味着,当你要求,你需要检查你的自我,直到你,你希望得到尽可能多的数据,你不一定得到尽可能多的数据。
That means that you don't necessarily get as much data as you request, you need to check your self until you got as much data as you expect.
int toRead = (int)length;
int read = 0;
while (toRead > 0)
{
int noChars = networkStream.Read(buffer, read, toRead);
read += noChars;
toRead -= noChars;
}
这篇关于从Java发送文件到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文