To send and receive a file as a byte array over sockets in Java, you can follow these steps. In this example, I'll demonstrate how to send a file from the client to the server. You can adapt the code for your specific needs.
Server (Receiver):
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(12345)) { System.out.println("Server is waiting for a connection..."); Socket clientSocket = serverSocket.accept(); System.out.println("Connection established with " + clientSocket.getInetAddress()); InputStream inputStream = clientSocket.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream("received_file.txt"); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, bytesRead); } System.out.println("File received successfully."); fileOutputStream.close(); inputStream.close(); clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } Client (Sender):
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try (Socket socket = new Socket("localhost", 12345)) { System.out.println("Connected to server."); File fileToSend = new File("file_to_send.txt"); FileInputStream fileInputStream = new FileInputStream(fileToSend); OutputStream outputStream = socket.getOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } System.out.println("File sent successfully."); outputStream.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } In this example:
The server waits for a connection on port 12345 and accepts it when a client connects.
The client connects to the server using the server's IP address and port number.
The client reads a file (file_to_send.txt) and sends it as a byte array to the server.
The server receives the byte array and writes it to a file (received_file.txt).
Both client and server close their streams and sockets when they are done.
Remember to replace "localhost" with the server's actual IP address if the server is running on a different machine.
This is a basic example, and in practice, you may want to add error handling, file existence checks, and more robust communication protocols for handling different file types and scenarios.
navbar youtube-data-api e-commerce apache-poi stripe-payments recode signal-handling grpc-java linux-mint project-reference