通过套接字发送文件

Gia*_*nis 2 java sockets networking

你好,我试图在java中使用客户端 - 服务器类发送文件.出于某种原因,当调用发送文件的方法时,套接字关闭.这是代码:

FileInputStream fIn = new FileInputStream(file);
out = new BufferedOutputStream(clientSocket.getOutputStream());
byte fileContent[] = new byte[(int) file.length()];
fIn.read(fileContent);
for (byte b : fileContent) {
    out.write(b);
}
Run Code Online (Sandbox Code Playgroud)

和来自客户端的代码:

FileOutputStream fIn = new FileOutputStream("testing");
BufferedInputStream inAout = new BufferedInputStream(clientSocket.getInputStream());
byte fileContent[] = new byte[1000000];
inAout.read(fileContent);
fIn.write(fileContent);
Run Code Online (Sandbox Code Playgroud)

和我得到的错误消息:SEVERE:null java.net.SocketException:Socket关闭

我真的没有经验,所以如果有任何可以帮助它将是伟大的.

Whi*_*g34 14

InputStream.read(byte[])方法返回一个int实际读取的字节数.不能保证读取字节数组中请求的字节数.它通常会返回底层缓冲区的大小,你必须多次调用它.

通过将字节从套接字流式传输到文件而不是缓冲内存中的整个字节数组,可以更有效地使用它.同样在服务器端,您可以执行相同的操作来节省内存,并且比一次写入一个字节更快.

这是一个服务器和客户端的工作示例,它连接到自身以传输文件:

public class SocketFileExample {
    static void server() throws IOException {
        ServerSocket ss = new ServerSocket(3434);
        Socket socket = ss.accept();
        InputStream in = new FileInputStream("send.jpg");
        OutputStream out = socket.getOutputStream();
        copy(in, out);
        out.close();
        in.close();
    }

    static void client() throws IOException {
        Socket socket = new Socket("localhost", 3434);
        InputStream in = socket.getInputStream();
        OutputStream out = new FileOutputStream("recv.jpg");
        copy(in, out);
        out.close();
        in.close();
    }

    static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buf = new byte[8192];
        int len = 0;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
    }

    public static void main(String[] args) throws IOException {
        new Thread() {
            public void run() {
                try {
                    server();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        client();
    }
}
Run Code Online (Sandbox Code Playgroud)