我想将文件从客户端发送到服务器,并且将来能够再次执行此操作。
所以我的客户端连接到服务器并上传文件,好的 - 它可以工作,但最后挂起..
这是我在客户端的代码,服务器端非常相似。
private void SenderFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
IoUtil.copy(fis, os);
} catch (Exception ex) {
ex.printStackTrace();
}
}
在堆栈上找到 IoUtils :)
public static class IoUtil {
private final static int bufferSize = 8192;
public static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[bufferSize];
int read;
while ((read = in.read(buffer, 0, bufferSize)) != -1) {
out.write(buffer, 0, read);
}
out.flush();
}
}
解释:我的客户端有一个连接到服务器的套接字,我向他发送任何文件。 我的服务器下载了它,但最后挂起,因为他正在监听更多信息。 如果我选择另一个文件,我的服务器会将新数据下载到现有文件中。
如何将任何文件上传到服务器,使我的服务器正常工作并能够正确下载另一个文件?
ps。如果我在函数 out.close
末尾添加到 ioutil.copy,我的服务器将继续工作,但连接将会丢失。我不知道该怎么办:{
更新后: 客户端:
private void SenderFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
DataOutputStream wrapper = new DataOutputStream(os);
wrapper.writeLong(file.length());
IoUtil.copy(fis, wrapper);
} catch (Exception ex) {
ex.printStackTrace();
}
}
服务器端(线程监听来自客户端的任何消息):
public void run() {
String msg;
File newfile;
try {
//Nothing special code here
while ((msg = reader.readLine()) != null) {
String[] message = msg.split("\\|");
if (message[0].equals("file")) {//file|filename|size
String filename = message[1];
//int filesize = Integer.parseInt(message[2]);
newfile = new File("server" + filename);
InputStream is = socket.getInputStream();
OutputStream os = new FileOutputStream(newfile);
DataInputStream wrapper = new DataInputStream(is);
long fileSize = wrapper.readLong();
byte[] fileData = new byte[(int) fileSize];
is.read(fileData, 0, (int) fileSize);
os.write(fileData, 0, (int) fileSize);
System.out.println("Downloaded file");
} else
//Nothing special here too
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
好的,现在我可以下载文件 - 还是一次,另一个已下载但无法读取。例如,第二次我想由客户端发送一个 file.png。我在服务器上找到了它,但无法查看该文件。 预先感谢:)
最佳答案
您需要使您的服务器能够区分文件。最简单的方法是提前告知接收端应该期望单个文件有多少字节;这样,它就知道何时停止阅读并等待下一篇。
这就是 SenderFile
方法的样子:
private void SenderFile(File file)
{
try
{
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
DataOutputStream wrapper = new DataOutputStream(os);
wrapper.writeLong(file.length());
IoUtil.copy(fis, wrapper);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
这就是 ReceiveFile
方法的样子:
// the signature of the method is complete speculation, adapt it to your needs
private void ReceiveFile(File file)
{
FileOutputStream fos = new File(file);
InputStream is = socket.getInputStream();
DataInputStream wrapper = new DataInputStream(is);
// will not work for very big files, adapt to your needs too
long fileSize = wrapper.readLong();
byte[] fileData = new byte[fileSize];
is.read(fileData, 0, fileSize);
fos.write(fileData, 0, fileSize);
}
然后不要关闭套接字。
关于java - 从客户端向服务器发送文件并且不丢失连接,这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12331545/