多线程上传图片功能

2017-10-24  本文已影响288人  简书超级会员
1.多线程上传图片的客户端
package controller.UploadImage;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TcpSendImage {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8080);
        OutputStream out = socket.getOutputStream();
        //创建字节的输入流,读取本机的图片
        FileInputStream fis = new FileInputStream("/Users/shangri-la/Pictures/timg.jpg");
        // 开始读写字节数组
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fis.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        // 给服务器终止方法
        socket.shutdownOutput();
        // 获取字节的输入流
        InputStream in = socket.getInputStream();
        System.out.println((new String(bytes, 0, in.read(bytes))));
        fis.close();
        socket.close();

    }
}

2.多线程上传图片的服务器TcpImageRunable接口
package controller.UploadImage;

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

public class TcpImageRunable implements Runnable {

    private Socket socket;

    public TcpImageRunable(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            InputStream in = socket.getInputStream();
            // 将目的文件夹封装到File对象
            File upload = new File("/Users/shangri-la/upload");
            if (!upload.exists()) {
                upload.mkdirs();
            }

            // 文件名规则:域名+时间戳+6位的随机数
            String fullName = upload + "/itcost" + System.currentTimeMillis() + new Random().nextInt(6) + ".jpg";

            //创建字节的输出流,将图片写到目的文件夹中
            FileOutputStream fos = new FileOutputStream(fullName);
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = in.read(data)) != -1) {
                fos.write(data, 0, len);
            }
            OutputStream out = socket.getOutputStream();
            out.write("上传成功".getBytes());

            fos.close();
            socket.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

3.多线程上传图片的服务器TCPThreadServer调用Thread类的start()方法
package controller.UploadImage;

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

public class TCPThreadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new TcpImageRunable(socket)).start();
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读