Java 通过套接字发送和接收文件(字节 [])
我正在尝试开发一个非常简单的客户端/服务器,其中客户端将文件转换为字节,将其发送到服务器,然后将字节转换回文件。
目前,该程序只是创建一个空文件。我不是一个出色的Java开发人员,所以任何帮助都非常感谢。
这是接收客户端发送的内容的服务器部分。
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(4444);
Socket socket = null;
socket = serverSocket.accept();
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte[] bytes = new byte[1024];
in.read(bytes);
System.out.println(bytes);
FileOutputStream fos = new FileOutputStream("C:\\test2.xml");
fos.write(bytes);
这是客户端部分
Socket socket = null;
DataOutputStream out = null;
DataInputStream in = null;
String host = "127.0.0.1";
socket = new Socket(host, 4444);
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
File file = new File("C:\\test.xml");
//InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
//out.write(bytes);
System.out.println(bytes);
out.close();
in.close();
socket.close();