• 简版的文件传输


    利用TCP协议下一个简版的文件传输

    发送文件客户端

     1 package Package1;
     2 
     3 import java.io.BufferedInputStream;
     4 import java.io.BufferedOutputStream;
     5 import java.io.File;
     6 import java.io.FileInputStream;
     7 import java.io.IOException;
     8 import java.net.InetAddress;
     9 import java.net.Socket;
    10 import java.net.UnknownHostException;
    11 
    12 public class 发送文件客户端 {
    13 
    14     public static void main(String[] args) throws IOException, IOException {
    15         try(
    16                 Socket s=new Socket(InetAddress.getByName("localhost"),9002);
    17                 BufferedInputStream  bis=new BufferedInputStream(new FileInputStream(new File("C:\Users\Administrator\Desktop\4.19.txt")));
    18                 BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
    19                 
    20                 ){
    21                     byte[] bt=new byte[1024];
    22                     int count=0;
    23                     while((count=bis.read(bt))!=-1) {
    24                         bos.write(bt,0,count);
    25                     }
    26                     bos.flush();
    27         }catch(Exception e) {
    28             e.printStackTrace();
    29         }
    30 
    31     }
    32 
    33 }

    服务器端:

     1 package Package1;
     2 
     3 import java.io.BufferedInputStream;
     4 import java.io.BufferedOutputStream;
     5 import java.io.File;
     6 import java.io.FileOutputStream;
     7 import java.io.IOException;
     8 import java.net.ServerSocket;
     9 import java.net.Socket;
    10 
    11 public class 发送文件服务器端 {
    12 
    13     public static void main(String[] args) throws Exception {
    14         try(
    15                 ServerSocket ss=new ServerSocket(9002);
    16                 
    17                 ){
    18                     try(
    19                             Socket s=ss.accept();
    20                         BufferedInputStream bis=new BufferedInputStream(s.getInputStream());                        
    21                         BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File("upload\2.txt")));
    22                             
    23                             ){
    24                             byte[] bt=new byte[1024];
    25                             int count=0;
    26                             while((count=bis.read())!=-1) {
    27                                 bos.write(bt,0,count);
    28                             }
    29                     }
    30         }
    31 
    32     }
    33 
    34 }
  • 相关阅读:
    Python-装饰器进阶
    JavaScript-CasperJs使用教程
    Python-第三方库requests详解
    PHP-PHP程序员的技术成长规划(By黑夜路人)
    Bootstrap-学习系列
    CSS-常用媒体查询
    Git-随笔
    工具-各种开源
    PHP-PHP5.3及以上版本中检查json格式的方法
    VIM-技巧
  • 原文地址:https://www.cnblogs.com/ywzbky/p/10741137.html
Copyright © 2020-2023  润新知