设计需求:从客户端上传txt文件到服务器,服务端收到文件后,发送消息给客户端接收完成。

1. 服务器端:

public class UpLoadFileServer {

public static void main(String[] args) throws Exception {

ServerSocket ss = new ServerSocket(10010);

Socket s =ss.accept();

BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));

BufferedWriter bufw =new BufferedWriter(new FileWriter("D:\\server.txt"));

String line1 =null;

while((line1=bufin.readLine())!=null)
{
bufw.write(line1,0,line1.length());
}

System.out.println("服务端接收完了。。。。");
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
out.println("上传成功");
System.out.println("服务端反馈客户端完了。。。。");

bufw.close();


s.close();
ss.close();

}
}

2. 客户端:

public class UploadFileClient {

public static void main(String[] args) throws Exception {

Socket s = new Socket("192.168.5.163",10010);

File file =new File("d:\\1.txt");

BufferedReader buffer =new BufferedReader(new FileReader(file));

PrintWriter out = new PrintWriter(s.getOutputStream(),true);

String line =null;

while((line=buffer.readLine())!=null)
{
out.println(line);
System.out.println("客户端读取文件里的内容"+line);
}

System.out.println("客户端发完了 。。。。。");
BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));
s.shutdownOutput();
String result=bufin.readLine();
System.out.println("客户端接收到了服务器的数据了 。。。。。");
System.out.println(result);

buffer.close();
s.close();
}
}

   小总结:之前运行一直不成功,进行调试发现,是客户端这边数据已经传输完了,但是服务器端还一直在等待客户端继续传递数据过来,而且一直没有把接收到的数据写到文件内。后在客户端增加:s.shutdownOutput();就能成功上传文件。

相关文章:

  • 2022-01-05
  • 2022-12-23
  • 2021-06-16
  • 2021-04-04
  • 2022-01-04
  • 2022-01-24
  • 2022-01-12
  • 2021-05-25
猜你喜欢
  • 2022-02-25
  • 2022-12-23
  • 2021-09-07
  • 2021-12-01
  • 2022-01-15
  • 2021-05-16
  • 2022-12-23
相关资源
相似解决方案