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<String> ips = new HashSet<String>();
    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();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值