我一直在Google上搜寻几个小时,试图了解如何通过java套接字成功发送任何文件。我在网上发现了很多东西,但它们都没有为我工作,我终于碰到了对象输出/输入流以在服务器和客户端之间发送文件,这是迄今为止我发现的唯一工作,但它似乎只能通过连接到本地主机。例如,如果我从不同网络上的朋友计算机连接到服务器并发送失败的文件,套接字将关闭,并显示“读取超时”,然后在重新连接后不久,文件就不会被发送。如果我连接到服务器上的本地主机,并发送文件,它完美的作品。那么最新的问题以及如何解决?通过Java套接字发送文件
编辑:以下是更新代码..招式极为缓慢
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。目前我正在使用它来发送和显示图像。
什么是您尝试连接的套接字的IP地址和端口? – 2014-11-25 01:27:53
可能被防火墙阻止。 – 2014-11-25 01:29:12
我可以确认套接字能够完美地连接到服务器,它只有发送文件有问题。 (它仍然读取服务器发送的名称和其他内容) – 2014-11-25 01:29:47