gpt4 book ai didi

java - 通过 java 套接字发送文件

转载 作者:行者123 更新时间:2023-12-02 05:14:11 27 4
gpt4 key购买 nike

我已经在 Google 上搜索了几个小时,试图弄清楚如何通过 java 套接字成功发送任何文件。我在网上找到了很多东西,但似乎都不适合我,我终于遇到了对象输出/输入流来在服务器和客户端之间发送文件,这是迄今为止我发现的唯一有效的东西,但是它似乎只能通过与本地主机的连接来工作。例如,如果我从不同网络上的 friend 的计算机连接到服务器并发送文件失败,套接字会关闭并显示“读取超时”,然后在重新连接后不久,文件永远不会发送。如果我连接到服务器上的本地主机并发送文件,它就可以正常工作。那么问题是什么以及如何解决它?

编辑:下面是更新的代码..移动速度非常慢

public synchronized File readFile() throws Exception {
String fileName = readLine();
long length = dis.readLong();
File temp = File.createTempFile("TEMP", fileName);
byte[] buffer= new byte[1000];
int count=0;
FileOutputStream out = new FileOutputStream(temp);
long total = 0;
while (total < length && (count = dis.read(buffer, 0, (int)Math.min(length-total, buffer.length))) > 0)
{
System.out.println(total+" "+length+" "+temp.length()); //Just trying to keep track of where its at...
out.write(buffer, 0, count);
total += count;
}
out.close();
return temp;
}


public synchronized void writeFile(File file) throws Exception {
writeString(file.getName());
long length = file.length();
dos.writeLong(length);
byte[] buffer= new byte[1000];
int count=0;
FileInputStream in = new FileInputStream(file);
long total = 0;
while (total < length && (count = dis.read(buffer, 0, (int)Math.min(length-total, buffer.length))) > 0)
{
System.out.println(total+" "+length); //Just trying to keep track of where its at...
dos.write(buffer, 0, count);
total += count;
}
in.close();
}

客户端和服务器端都有writeFile和readFile。目前我正在使用它来发送和显示图像。

最佳答案

不要为此使用对象流。使用DataInputStreamDataOutputStream:

  1. 发送和接收文件名,包含 writeUTF()readUTF() .
  2. 发送和接收数据,如下:

    while ((count = in.read(buffer)) > 0)
    {
    out.write(buffer, 0, count);
    }

    您可以在两端使用此代码。 buffer可以是任何大于零的大小。它不需要是文件的大小,并且无论如何也不会扩展到大文件。

  3. 关闭套接字。

如果您需要发送多个文件,或者有其他需要保持套接字打开:

  • 发送文件前面的长度,用writeLong() ,然后用 readLong() 来阅读它并修改循环,如下:

    long length = in.readLong();
    long total = 0;
    while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length : (int)(length-total))) > 0)
    {
    out.write(buffer, 0, count);
    total += count;
    }

    并且不要关闭套接字。请注意,您必须测试 total 读取之前,您必须调整读取长度参数,以免超出文件末尾。

  • 关于java - 通过 java 套接字发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27117302/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com