TCP--通过多线程实现客户端并发上传图片

/*
通过多线程实现客户端并发上传图片

*/
import java.io.*;
import java.net.*;

class PicThread implements Runnable {
	private Socket s;
	PicThread(Socket s) {
		this.s = s;
	}
	public void run() {
		int count = 1;
		String ip = s.getInetAddress().getHostAddress();
		try {
			InputStream in = s.getInputStream();
			OutputStream out = s.getOutputStream();
			System.out.println(ip + "....connecting");

			File file = new File(ip + ".jpg");
			while(file.exists())
				file = new File(ip + "(" + (count ++) + ")" + ".jpg");

			FileOutputStream fos = new FileOutputStream(file);
			byte[] by = new byte[1024];
			int num = 0;
			while((num = in.read(by)) != -1) {
				fos.write(by, 0, num);
			}
			out.write("上传成功".getBytes());
			s.close();
			fos.close();

		} catch(Exception e) {
			throw new RuntimeException(ip + "上传失败");
		}
	}
}

class PicClient02 {
	public static void main(String[] args) throws Exception {
		/*
		if(args.length != 1) {
			System.out.println("...请输入一个正确的 .jpg 文件路径");
			return;
		}*/

		File file = new File(args[0]);

		if(! (file.exists() && file.isFile())) {
			System.out.println("...请检查该文件是否存在");
			return;
		}
		if(! file.getName().endsWith(".jpg")) {
			System.out.println("...只要 .jpg 格式的");
			return;
		}
		if(file.length() > 1024*1024*5) {
			System.out.println("...文件过大,没安好心");
			return;
		}

		Socket s = new Socket("172.16.41.154", 10005);
		InputStream in = s.getInputStream();
		OutputStream out = s.getOutputStream();

		FileInputStream fis = new FileInputStream(file);
		byte[] by = new byte[1024];
		int num = 0;
		while((num = fis.read(by)) != -1) {
			out.write(by, 0, num);
		}
		s.shutdownOutput();
		int count = in.read(by);	//接受服务端反馈的信息
		String info = new String(by, 0, count);	//直接利用上面的数组
		System.out.println(info);

		s.close();
	}
}

class PicServer02 {
	public static void main(String[] args) throws Exception {
		ServerSocket ss = new ServerSocket(10005);
		while(true) {
			Socket s = ss.accept();
			new Thread(new PicThread(s)).start();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值