Java File Transfer over Sockets: Sending and Receiving Byte Arrays
In Java, transferring files over sockets involves converting the file into byte arrays, sending them via the socket, and then converting the bytes back into a file at the receiving end. This article addresses an issue encountered by a Java developer in implementing this file transfer functionality.
Server-Side Issue
The server code appears to create an empty file upon receiving data from the client. To resolve this, the server should use a loop to read the data sent by the client in chunks, using a buffer to temporarily store the data. Once all data has been received, the server can write the complete file. The corrected server code is as follows:
1 2 3 4 5 |
|
Client-Side Issue
The client code initially sends an empty byte array to the server. To send the actual file content, the following code should be used:
1 2 3 4 |
|
Improved Code
With the aforementioned corrections, the full code for server and client is as follows:
Server:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
The above is the detailed content of How to Correctly Transfer Files Over Sockets in Java?. For more information, please follow other related articles on the PHP Chinese website!