黑马程序员--基础加强--第四篇--TCP多线程实现图片上传

ASP.Net+Android+IOS开发.Net培训期待与您交流!

多个客户端可以并发的上传图片到服务器中

import java.io.*;
import java.net.*;
class PicClient2{
	public static void main(String[] args){
		try{
			//获取客户端Socket,并绑定服务器主机和端口。
			Socket s = new Socket(InetAddress.getLocalHost(),10003);
			FileInputStream fs = new FileInputStream("d:/tempFile/QQ.png");
			OutputStream osOut = s.getOutputStream();
			byte[] buf = new byte[1024];
			int a = -1;
			//将图片读入流中,并写道Socket的OutputStream()流中
			while((a=fs.read(buf))!= -1){
				osOut.write(buf,0,a);
			}
			//给网络流加结束标记
			s.shutdownOutput();
			
			//读取服务器返回的数据信息
			InputStream osIn = s.getInputStream();
			byte[] arr = new byte[1024];
			int b = osIn.read(buf);
			System.out.println(new String(arr,0,b));
			
			osIn.close();
			osOut.close();
			fs.close();
			s.close();
		}catch(UnknownHostException  e){
			throw new RuntimeException("找不到服务器主机");
		}catch(IOException e){
			throw new RuntimeException("读写文件错误");
		}
		
	}
}
//如何实现多线程技术呢?只需将每个客户端的代码存入run方法中即可!

class SockThread implements Runnable{
	private Socket s;
	String ip;
	SockThread(Socket s ){
		this.s = s;
	}
	public void run(){
		try{
			//获取客户端ip地址
			ip = s.getLocalAddress().getHostAddress();
			System.out.println(ip+"connect");
			InputStream isIn = s.getInputStream();
			int count = 1;
			File f = new File("d:/tempFile/"+ip+"("+count+")"+".png");
			while(f.exists()){
				f = new File("d:/tempFile/"+ip+"("+(count++)+")"+".png");
			}
			
			//将客户端传过来的图片保存到一个文件夹中
			FileOutputStream fos = new FileOutputStream(f);
			byte[] buf = new byte[1024];
			int a = -1;
			while((a = isIn.read(buf))!=-1){
				fos.write(buf,0,a);
			}
			
			//往客户端写返回信息
			OutputStream osOut = s.getOutputStream();
			osOut.write("上传成功".getBytes());
			fos.close();
			isIn.close();
			osOut.close();
			s.close();
		}catch(IOException e){
			throw new RuntimeException(ip+"上传失败");
		}
	}
}
class PicServer2{
	public static void main(String[] args){
		try{
			ServerSocket ss = new ServerSocket(10003);
			while(true){
				//阻塞式等待客户端发来的请求
				Socket s = ss.accept();
				//启动线程并把客户端的Socket对象传入处理程序中
				new Thread(new SockThread(s)).start();
			}
		}catch(IOException e){
			throw new RuntimeException("服务器端接收失败");
		}
	}
}

运行结果为



ASP.Net+Android+IOS开发.Net培训期待与您交流!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值