为什么 java 套接字中的客户端文件会损坏?
我编写了一个java代码,它使用FileInputStream
和BufferedInputStream
将.exe
文件从服务器发送到客户端,但是该文件在以下位置被损坏客户端。
可能是什么原因?
command1= ServerFrame.msg1+".exe";
File p=new File(command1);
FileInputStream f=new FileInputStream(p);
BufferedInputStream bis=new BufferedInputStream(f);
Integer d=bis.available();
int d1=d;
byte b[]=new byte[d];
bis.read(b,0,d1);
System.out.println(d1);
dos=new DataOutputStream(s.getOutputStream());
BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
dos.writeUTF(d.toString()); // sending length in long
bos.write(b,0,d1); // sending the bytess
bos.flush();
bis.close();
bos.close();
dos.close();
I have written a java code which sends a .exe
file from the server to the client using FileInputStream
and BufferedInputStream
, but the file gets corrupted at the client side.
What could be the reason?
command1= ServerFrame.msg1+".exe";
File p=new File(command1);
FileInputStream f=new FileInputStream(p);
BufferedInputStream bis=new BufferedInputStream(f);
Integer d=bis.available();
int d1=d;
byte b[]=new byte[d];
bis.read(b,0,d1);
System.out.println(d1);
dos=new DataOutputStream(s.getOutputStream());
BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
dos.writeUTF(d.toString()); // sending length in long
bos.write(b,0,d1); // sending the bytess
bos.flush();
bis.close();
bos.close();
dos.close();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想
s
是你的套接字。您的代码中几乎没有什么可以修改的:bis.available()
返回可以在不阻塞的情况下读取的字节数,而不是文件的总大小,您应该使用循环来读取您在两个不同缓冲区中使用输出流的文件这是您打算执行的操作:
I suppose that
s
is your socket. There are few thing that can be wong in your code:bis.available()
returns the number of bytes that can be read without bocking, not the total size of the file, you should use a loop to read the fileHere is what you intend to do:
bis.available() 返回可供读取的字节,它可能不是完整的内容大小,您必须循环读取直到到达 EOF。
bis.available() returns the bytes available for read, it may not be the full content size, u have to read in a loop till it reaches EOF.
如果有人遇到同样的问题,缓冲区大小是这种情况下的罪魁祸首:
应该较小,尝试 1024 或其他东西:
希望这会有所帮助..
in case someone stuck with same problem, buffer size is the culprit in this case :
It should be lesser try 1024 or something:
hope this helps..