Java

java socket传输大文件的方法

小樊
141
2024-06-27 18:17:25
栏目: 编程语言

在Java中,可以通过Socket来传输大文件。以下是一个简单的例子来说明如何在Java中使用Socket传输大文件:

  1. 服务器端代码:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(12345);
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.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);
        }

        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}
  1. 客户端代码:
import java.io.*;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 12345);

        File file = new File("large_file.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        OutputStream outputStream = socket.getOutputStream();

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        fileInputStream.close();
        outputStream.close();
        socket.close();
    }
}

在上面的代码中,服务器端监听端口12345,客户端连接到服务器端的12345端口。客户端发送名为"large_file.txt"的大文件到服务器端,并且服务器端接收并保存为"received_file.txt"文件。

通过Socket传输大文件时,需要注意以下几点:

0
看了该问题的人还看了