首页 > 解决方案 > Java 套接字服务器发送大文件

问题描述

我正在尝试制作一个服务器,它接收客户端发送的一些大文件并在另一个位置创建相同的文件(基本上下载该文件并将其移动到另一个地方)。问题是服务器在尝试发送大文件时冻结。服务器.java:

    package testing_server;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

public class Server {
    public static void main(String[] args) throws IOException, InterruptedException
    {
    ServerSocket server = new ServerSocket(2000);

    Client client2 =  new Client();
    client2.main("");   
    
    while (true)
    {   
        
        Socket client = server.accept();
        DataInputStream in = new DataInputStream(client.getInputStream());
        
        int a;
        byte[] buffer = new byte[1025];

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        while ((a= in.read(buffer))!=-1 )
            {
            bos.write(buffer,0,a);
            bos.flush();
            System.err.println(a);
            }
        

        
    }

}
}

这是 Client.java

package testing_server;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Iterator;

public class Client {
public static void main(String args) throws UnknownHostException, IOException, InterruptedException
{
    Socket server = new Socket("ip",2000);
    DataOutputStream out =  new DataOutputStream(server.getOutputStream());

    final FileChannel channel = new FileInputStream("test.jpg").getChannel();
    MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    byte[] ar = new byte[1025];
    //this is only for testing 
    int many = buffer.capacity()/1025;
    
    int i  =0;
    while (i<=many)
    {
        buffer.get(ar);
        out.write(ar,0,1025);
        out.flush();
        
    
        i++;    
    }

    
    // when finished
    channel.close();
    out.close();
    server.close();
}
}

我怎样才能在不冻结的情况下发送这个大文件。我可以只发送一份这样我就不会丢失字节吗?如果不是,我怎么能设法在发送块时不丢失字节?我提到该文件为 10MB,因此它不是一个很大的文件。我想在不压缩的情况下管理它。

标签: javaservertcp

解决方案


推荐阅读