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();
    }

}

 

posted @ 2021-07-14 14:47  下饭  阅读(33)  评论(0编辑  收藏  举报