gpt4 book ai didi

java - 无法通过 LAN 将文件从服务器发送到客户端

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:48 25 4
gpt4 key购买 nike

这是服务器端和客户端的代码片段,用户可以通过它们向服务器请求文件。服务器将发送文件。

有两个问题:

  • 服务器端发送空文件。
  • 尝试在局域网中运行代码时出现 ioException

我不明白为什么服务器发送空文件,请帮忙。

服务器端代码:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ftpserverclient.FileClientServer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
*
* @author Arnab
*/
public class FileServer {

public static void main(String args[])throws IOException
{
ServerSocket ss=null;
try
{
ss=new ServerSocket(8085);
}
catch(IOException e)
{
System.out.println("couldn't listen");
System.exit(0);
}
Socket cs=null;
try
{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();


String path = s ;
System.out.println("The requested file is path: "+path);
System.out.println("The requested file is : "+s);
File f=new File(path);
if(f.isFile())
{
BufferedReader d=new BufferedReader(new FileReader(f));
String line;
while((line=d.readLine())!=null)
{
put.write(line);
put.flush();
}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}
}

}

客户端代码:

package ftpserverclient.FileClientServer;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
*
* @author Arnab
*/
public class FileClient {

public static void main(String srgs[])throws IOException
{
Socket s=null;
BufferedReader get=null;
PrintWriter put=null;
try
{
s=new Socket("127.0.0.1",8085);
get=new BufferedReader(new InputStreamReader(s.getInputStream()));
put=new PrintWriter(s.getOutputStream(),true);

String u,f;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);

File f1=new File(f);



FileOutputStream fs=new FileOutputStream(new File("C:\\PictureDestination\\a.jpg"));


while((u=get.readLine())!=null)
{
System.out.println(u);
byte jj[]=u.getBytes();
fs.write(jj);
}
fs.close();
System.out.println("File received");
s.close();
}catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
}

}

最佳答案

在客户端,在将文件名发送到服务器时,您忘记在 put.println(f); 之后写入 put.fflush();

关于java - 无法通过 LAN 将文件从服务器发送到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21349796/

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