如何使用套接字通道通过网络发送图像文件
我创建了服务器程序,它将向客户端发送图像文件。 如果图像是 512 字节,我的程序可以正常工作。 但对于大文件来说它确实工作得很好。
在这种情况下,我没有得到我应该得到的确切图像。 意味着我恢复的图像存在某种不正确的方式。 那么如何解决这个问题
我在服务器中使用java套接字通道和java nio,而在客户端使用简单的套接字。
谢谢 苏尼尔
I have created server program which will send an image file to the client.
My program works fine if the image is of 512 byte. But it does nit work fine for large file.
In this case i am not getting the exact image that i am supposed to get. means my recovered image is in some improper manner. So how to solve this problem
I am using java socket channel and java nio in server while simple socket in client side.
Thanks
Sunil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没有看到您在客户端刷新并关闭输出流。 当你退出时,你应该 close() 输出流,所有缓存的数据都将被写到文件中。
I don't see you flushing and closing your output stream on the client side. When you break out you should close() the output stream, and any cached data will be written out to the file.
这是您的错误:
read()
方法不一定会填充缓冲区; 它将读取任意数量的字节并返回该数字。 您必须考虑到读取小于缓冲区容量并仅写入那么多字节的情况,这也是必要的,因为文件大小不一定是缓冲区大小的倍数,并且最后一次读取几乎永远不会完全填充缓冲区。在客户端也是如此 -
available()
在这里没有用,您必须简单地读取然后处理您获得的字节数。Here's your bug:
The
read()
method will not necessarily fill the buffer; it will read an arbitrary number of bytes and return that number. You have to allow for the case that it reads less than the buffer's capacity and write only that many bytes, which is also necessary since the file size is not necessarily a multiple of your buffer size and the last read will almost never exactly fill the buffer.The same is true on the client side -
available()
is not useful here, you have to simply read and then deal with however many bytes you got.