• 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();
        }
    
    }
  • 相关阅读:
    hdu 5253 最小生成树
    hdu5248 序列变换
    bjfu1299 stl使用
    bjfu1277 简单递归
    bjfu1262 优先队列
    bjfu1287字符串输出的大水题
    bjfu1281
    bjfu1253 最大上升子序列和
    [转][Unity3D]引擎崩溃、异常、警告、BUG与提示总结及解决方法
    Unity3d 中 将远程 MySQL 数据库转换为本地 Sqlite
  • 原文地址:https://www.cnblogs.com/yxj808/p/15010796.html
Copyright © 2020-2023  润新知