zoukankan      html  css  js  c++  java
  • tcp编程:文件上传

    package com.sundear.demo.tcp;
    
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /**
     * 创建服务器
     * 1。指定端口 使用ServerSocket创建服务器
     * 2,阻塞式等待连接 accept
     * 3. 操作 输入输出流操作
     * 4。 释放资源
     */
    public class FileServer {
        public static void main(String[] args) throws IOException {
            System.out.println("---server---");
            //指定端口 使用ServerSocket创建服务器
            ServerSocket server = new ServerSocket(8888);
            //阻塞式等待连接 accept
            Socket client = server.accept();
            System.out.println("一个客户端建立了连接");
            //2.操作 文件拷贝
         BufferedInputStream is = new BufferedInputStream(client.getInputStream());
            BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream("src/main/java/com/sundear/demo/tcp/tcp.png"));
            byte[] flush = new byte[1024];
            int len=-1;
            while((len= is.read(flush))!=-1){
                bf.write(flush,0,len);
            }
            bf.flush();
            bf.close();
            client.close();
        }
    }
    

      

    package com.sundear.demo.tcp;
    
    import java.io.*;
    import java.net.Socket;
    
    /**
     * 单向:创建客户端
     * 1。建立连接 使用Socket创建客户端+服务的地址和端口
     * 2. 操作 输入输出流操作
     * 3。 释放资源
     */
    public class FileClient {
        public static void main(String[] args) throws IOException {
            System.out.println("---client---");
            Socket client =new Socket("localhost",8888);
            //2.操作 文件上传
            BufferedInputStream bf = new BufferedInputStream(new FileInputStream("src/main/java/com/sundear/demo/tcp/1.png"));
            BufferedOutputStream os = new BufferedOutputStream(client.getOutputStream());
            byte[] flush = new byte[1024];
            int len=-1;
            while((len= bf.read(flush))!=-1){
                os.write(flush,0,len);
            }
            os.flush();
            os.close();
            client.close();
        }
    
    }
  • 相关阅读:
    快考试了
    16号了
    终于找到网吧了,写写今天
    又打了一天的篮球
    (转载)Andoid2.X各字段意义
    (转载)AndroidMatrixCursor
    (转载)非常好 必须要顶
    (转载)Android Cursor之MergeCursor
    七天开发安卓软件(二)
    “Visual Studio.net已检测到指定的Web服务器运行的不是Asp.net1.1版。您将无法运行Asp.net Web应用程序或服务”问题的解决方法
  • 原文地址:https://www.cnblogs.com/yxj808/p/15010796.html
Copyright © 2011-2022 走看看