Java 网络编程——多线程下载图片

利用TCP连接实现+多线程模拟实现客户端服务端下载图片过程

服务端代码

package test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;


public class ImageServer extends Thread {

    Socket socket;

    static HashSet ips = new HashSet();
    public ImageServer(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            OutputStream outputstream = socket.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream("D:\\1.jpg");
            byte[] buf = new byte[1024];
            int length = 0;
            while((length = fileInputStream.read(buf))!=-1) {

                outputstream.write(buf,0,length);
            }
            String ip = socket.getInetAddress().getHostAddress();
            if(ips.add(ip)) {
                System.out.println("恭喜" + ip + "同学下载成功!");
            }
            fileInputStream.close();
            socket.close();

        } catch (IOException e) {
            // TODO: handle exception
        }
    }

    public static void main(String[] args) throws IOException{
        ServerSocket serverSocket = new ServerSocket(7070);
        while(true) {
            Socket socket = serverSocket.accept();
            new ImageServer(socket).start();
        }
    }
}

客服端代码

package test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;

public class ImageClient {

    public static void main(String[] args) throws IOException {

        Socket socket = new Socket(InetAddress.getLocalHost(), 7070);
        InputStream inputStream = socket.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\2.jpg");
        byte[] buf = new byte[1024];
        int length = 0;
        while( (length = inputStream.read(buf)) != -1    ) {
            fileOutputStream.write(buf, 0, length);
        }
        fileOutputStream.close();
        socket.close();
    }

}

你可能感兴趣的:(Java)