TCL协议传输文件

发送端

System.out.println("上传客户端已启动....");
//1.创建Socket对象
    Socket s = new So cket(InetAddress.getLocalHost().getHostAddress(), 10010); 
//2.读取文本文件(读取本地文件)
    BufferedReader br = new BufferedReader(new FileReader("a.txt"));
//3.准备输出流(向服务器输出)
    OutputStream out = s.getOutputStream();
    PrintWriter pw = new PrintWriter(out, true);
    String line = null;
    while((line=br.readLine())!= null) {
        pw.println(line);
    }  
    //客户端发送完毕后,要通知服务器我这边已经结束了..
    //!!结束标记
    s.shutdownOutput();//关闭输出流  

    //接收服务器返回的状态,是否上传成功
    InputStream is = s.getInputStream();
    byte[] b = new byte[1024];
    int len = is.read(b);
    System.out.println("result : " + new String(b,0,len)); 

//4.关闭资源
    br.close();
    s.close();

接收端

System.out.println("上传服务器已准备....");
//1.创建ServerSocket对象
    ServerSocket ss = new ServerSocket(10010); 
//2.获取Socket对象
    Socket socket = ss.accept();
//3.获取输入流
    InetAddress ip = socket.getInetAddress();
    System.out.println(ip + "....已建立连接....");
    InputStream is = socket.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    //创建File对象指向 upload文件夹
    File dir = new File("D:\\asd");
    //判断文件夹是否存在
    if(!dir.exists()) {
        //不存在,就创建文件夹
        dir.mkdirs();
    }
    BufferedWriter bw = new BufferedWriter(new FileWriter(new File(dir, ip+".txt")));
    String line = null;
    while((line=br.readLine())!= null ) {
        bw.write(line);
        bw.newLine();
        bw.flush();
    }
    System.out.println("文件上传完毕...."); 
    //上传成功
    OutputStream out = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(out,true);
    pw.println("上传成功.");

    //关闭资源
    bw.close();
    socket.close();
    ss.close();

你可能感兴趣的:(z)