java - 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,因此它不是一个很大的文件。我想在不压缩的情况下管理它。
解决方案
推荐阅读
- javascript - 使用我当前工作的 Git 分支名称在 dist 内生成一个文件夹。我们目前正在使用 Angular Js 和 webpack
- powerbi - Power BI 中的时间动态存储桶
- python - 带有 keras 和遮罩层的可变长度序列
- ios - 如何使用 MagicalRecord for Swift 4 正确获取数据?
- python - 在python中抓取,选择器返回空列表
- python-3.x - 从标题中删除引号
- sql - Postgresql - 三张表。两个连接。不相关的结果
- javascript - React - “异步加载的外部脚本”错误
- c++ - 打开 SSL 简单加密/解密 C++
- nativescript - 带有 YoutubePlayer 插件的 NativeScript-Vue 在 Android 中不起作用