简体   繁体   English

DataOutputStream不发送-1

[英]DataOutputStream doesn't send -1

I'm trying to make a sending option for a chat client and I was able to do it for small files but then I got a problem when I tried to do it with big ones. 我正在尝试为聊天客户端制作一个发送选项,我能够为小文件做这个,但是当我尝试用大文件时,我遇到了问题。 The way I tried to solve it was: Client side,read from file and send: 我试图解决它的方式是:客户端,从文件读取并发送:

while ((buf = bin.read(bytearray, 0, bytearray.length)) != -1) {
     os.write(bytearray,0,bytearray.length);
}
bin.close();

"bin" is my bufferedInputStream from a fileInputStream, "buf" is just an integer, os is my DataOutputStream. “bin”是来自fileInputStream的bufferedInputStream,“buf”只是一个整数,os是我的DataOutputStream。 Server side, receive and send: 服务器端,接收和发送:

while ((buf = in.read(bytes, 0, bytes.length)) != -1) {
dos.write(bytes,0,bytes.length);
}

"in" is the DataInputStream, "buf" is an integer, "dos" is a DataOutputStream(it does this for all clients) Client side, receive file from server and write to hard drive: “in”是DataInputStream,“buf”是整数,“dos”是DataOutputStream(它为所有客户端执行此操作)客户端,从服务器接收文件并写入硬盘:

int buf;
while ((buf = in.read(bytes, 0, bytes.length)) != -1) {
     fos.write(bytes,0,bytes.length);
}
fos.close();

Here "in" is a DataInputStream, "fos" is a FileOutputStream. 这里“in”是DataInputStream,“fos”是FileOutputStream。 What happens is that when I hit the send button on first client, both the server and the client start receiving the file, but it gets received only when I close the second client(receiver) because that's when the socket closes and probably that's when it actually decides to stop receiving and finish writing the file. 当我点击第一个客户端上的发送按钮时,服务器和客户端都开始接收文件,但只有当我关闭第二个客户端(接收器)时才会收到它,因为那是在套接字关闭的时候,可能就是当它关闭时实际上决定停止接收并完成文件的写入。 Please tell me why it doesn't receive that "-1" when the sending executes once and the dataInputStream should be empty in the server and therefore cause that "-1"? 请告诉我为什么当发送执行一次并且dataInputStream在服务器中应为空并因此导致“-1”时它没有收到“-1”?

DataOutputStream never sends -1. DataOutputStream 从不发送-1。 The underlying transport signals an EOS to the peer when you close the output stream, and that is returned by the read() API as -1 when encountered. 当您关闭输出流时,底层传输向对等体发出EOS信号,并且遇到时由read()API返回为-1。 There is no -1 on the wire. 电线上没有-1。 If you don't close the output stream, you won't receive the -1. 如果不关闭输出流,则不会收到-1。

If you want the reader to stop reading without closing the output stream, you will have to tell it somehow as part of your application protocol: for example, send a length word ahead of the data, and have the reader read exactly that many bytes. 如果您希望读取器在不关闭输出流的情况下停止读取,则必须以某种方式将其作为应用程序协议的一部分进行说明:例如,在数据之前发送一个长度字,并让读取器读取多少字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM