且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过套接字发送大文件

更新时间:2022-03-02 08:39:33

你无法将文件的长度写入客户端中的流:

You failed to write out the length of the file to the stream in the client:

long size = clientData.readLong();

因此,服务器中的调用正在读取实际文件的前8个字节,谁知道这是什么数量是。您不必从流中读取长度,因为您只写了一个文件。读完文件名和用户名后(不是很安全吗?)你可以直到EOF读取流。如果您想通过同一个打开的套接字发送多个文件,那么在读取文件之前您需要知道长度。

So that call in the server is reading the first 8 bytes of the actual file and who knows what that quantity is. You don't have to read the length from the stream since you only wrote a single file. After reading the filename, and username (not very secure is it?) you can just read the stream until EOF. If you ever wanted to send multiple files over the same open socket then you'd need to know the length before reading the file.

此外,您的阅读缓冲区是通过小。您应该至少为8192而不是1024.并且您希望将所有.close()放在finally块中,以确保您的服务器和客户端在出现异常时正确关闭。

Also your buffers for reading are way to small. You should be at a minimum of 8192 instead of 1024. And you'll want to put all .close() in a finally block to make sure your server and clients shutdown appropriately if there is an exception ever.