美文网首页
TCP接收图片上传 多线程

TCP接收图片上传 多线程

作者: 勇者与王者 | 来源:发表于2019-10-07 14:01 被阅读0次

先将接收图片的代码放到 线程的run方法中

package Day32_Net;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;

/**
 * @Author quzheng
 * @Date 2019/10/7 12:30
 * @Version 1.0
 */
public class Upload implements Runnable{

    private Socket client;

    public Upload(Socket socket){
        this.client = socket;
    }
    @Override
    public void run() {
        try{
            String path = "D:\\360Downloads\\upload";
            //创建服务器本地的 输出流 即 写字节到本地

            //创建文件夹对象
            File f = new File(path);
            //如果文件夹不存在,则自动创建该目录
            if ( !f.exists()){
                f.mkdirs();
            }

            //使用 毫秒值加随机数生成图片文件名
            String filename = "upload"+System.currentTimeMillis()+new Random().nextInt(9999)+".png";
            //使用 File.separator获取系统分隔符
            FileOutputStream fos = new FileOutputStream(path+File.separator+filename);



            // 获取到客户端的 输入流 即 服务器要接收的流
            InputStream in = client.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ( ( len = in.read(bytes)) != -1  ){
                fos.write(bytes,0,len);
            }

            // 获取到 客户端的 输出流 来向客户端发送消息
            OutputStream out = client.getOutputStream();
            out.write("上传成功".getBytes());



            fos.close();
            client.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}

再无限循环调用线程的run方法 ,不停的接收客户端socket连接

package Day32_Net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author quzheng
 * @Date 2019/10/7 13:29
 * @Version 1.0
 *
 * TCP 多线程服务器上传
 */
public class TCPThreadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(9999);

        while(true){
            Socket client = server.accept();
            new Thread( new Upload(client) ).start();
        }

    }
}

相关文章

网友评论

      本文标题:TCP接收图片上传 多线程

      本文链接:https://www.haomeiwen.com/subject/mvlmpctx.html