zoukankan      html  css  js  c++  java
  • java 网络编程(五)----TCP进阶篇上传文本文件

    设计需求:从客户端上传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();就能成功上传文件。

  • 相关阅读:
    eyoucms遍历子栏目,有二级栏目的点击展开或者收缩
    eyoucms 遍历栏目下的子栏目
    帝国cms 内容页根据关键词来调用相关内容
    帝国cms 上传的图片前台不显示
    帝国cms 通过字段内容来获取数据
    eyoucms 去掉 index.php后缀
    通过jquery插件复制文字
    帝国cms 表单弹窗提交,判断后才能提交到后台
    动态库和静态库
    J-520-2018年第二届河北省大学生程序设计竞赛(快速幂取模)
  • 原文地址:https://www.cnblogs.com/loleina/p/5174973.html
Copyright © 2011-2022 走看看