[英]Strange behaviour of InputStream / OutputStream in Socket
As always I'm having trouble with Streams and Sockets. 和往常一样,我在使用流和套接字时遇到了麻烦。
Here is my Code: 这是我的代码:
Client 客户
bitOut.write((f.getName() + "\n").getBytes());
//System.out.println(f.length()); // <- This is the odd part.
bitOut.write((int) f.length());
bitOut.flush();
fileIn = new FileInputStream(f);
byte buffer[] = new byte[BUFFER_SIZE];
int len;
while ((len = fileIn.read(buffer)) != -1) {
bitOut.write(buffer, 0, len);
}
fileIn.close();
Server 服务器
file = sc.nextLine();
int fileSize = bitIn.read(); // <- Here is my error!
System.out.println(file + ", " + fileSize);
fileOut = new FileOutputStream(folder + file);
byte buffer[] = new byte[BUFFER_SIZE];
int len;
while (fileSize > 0 && (len = bitIn.read(buffer)) != -1) {
fileOut.write(buffer, 0, len);
fileSize -= len;
System.out.println(fileSize);
}
fileOut.close();
If I uncomment the System.out.println(f.length())
in the client code, the server is always getting the right value in fileSize
. 如果我在客户端代码中取消注释System.out.println(f.length())
,则服务器始终会在fileSize
获得正确的值。 But if I leave it commented, fileSize
is often a byte from the data which should be sent after f.length()
. 但是,如果我不评论,则fileSize
通常是应该在f.length()
之后发送的数据中的一个字节。 On the one hand it's funny because almost only if I print out the file size in the client, I receive the right result on the server. 一方面,这很有趣,因为几乎只有当我在客户端中打印出文件大小时,我才能在服务器上收到正确的结果。 On the other hand I got no clue how to fix it... 另一方面,我不知道如何解决它。
Ok I solved it. 好的,我解决了。 It was something with the Scanner, whose method nextLine()
swallowed the byte I was sending after the file name. 扫描仪就是这样,它的方法nextLine()
吞噬了我在文件名之后发送的字节。 Now I'm just using the normal InputStream
and OutputStream
. 现在,我只使用普通的InputStream
和OutputStream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.