TCP并发复制上传文件

/*
需求:上传图片

*/

/*
客户端:
1、建立服务
2、读取客户端已有数据
3、通过socket输出流,将数据发送到服务端
4、通过socket读取流,读取服务端返回信息
*/
import java.io.*;
import java.net.*;
import java.lang.Exception;
class  PicClient
{
	public static void main(String[] args) throws Exception
	{
		if(args.length != 1)
			System.out.println("请选择一个文件");

		File file = new File(args[0]);
		if(!file.exists() && file.isFile())
		{
			System.out.println("文件不存在或者不是文件。");
			return;
		}
		System.out.println(file.getName());
		if(!file.getName().endsWith(".jpg"))
		{
			System.out.println("请选择一个jpg文件");
			return;
		}
		Socket s = new Socket("222.49.250.147",10001);

		FileInputStream fis = new FileInputStream(file);
		OutputStream os = s.getOutputStream();
		byte[] buf =new byte[1024];
		int len = 0;
		while((len = fis.read(buf)) != -1)
		{
			os.write(buf,0,len);
		}

		//告诉服务端读入完毕
		s.shutdownOutput();

		//读取服务器端返回
		InputStream is = s.getInputStream();
		byte [] bufin = new byte[1024];
		int num = is.read(bufin);
		System.out.println(new String(bufin,0,num));
		fis.close();
		s.close();
	}
}

/*
实现多个客户端同时并发访问服务端,服务端最好就是将每个客户端封装到一个单独的线程中,
这样就可以同时处理多个客户端情况。
如何定义线程呢?
只要明确每个客户端要在服务端要执行的代码,将该代码存到run方法中即可。
*/
class PicServerThraed extends Thread
{
	Socket s = null;
	PicServerThraed(Socket s)
	{
		this.s = s;
	}

	public void run()
	{
		int count =1;
		try
		{
			String ip = s.getInetAddress().getHostAddress();
			System.out.println(ip + "connected");
			
			File file = new File(ip + "(" + count +")" + ".jpg");
			while(file.exists())
				file = new File((ip + "(" + count++ +")" + ".jpg"));
			InputStream is = s.getInputStream();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buf =new byte[1024];
			int len = 0;
			while((len = is.read(buf)) != -1)
			{
				fos.write(buf,0,len);
			}

			//将信息返回给客户端
			OutputStream os = s.getOutputStream();
			os.write("上传成功".getBytes());
			is.close();
			fos.close();
			os.close();
		}
		catch (Exception ex)
		{
		}
	}
}


/*
服务器端
*/
class PicServer
{
	public static void main(String [] args) throws Exception
	{
		ServerSocket ss = new ServerSocket(10001);
		while(true)
		{
			//由于accept方法时阻塞式的,所以当a进来的时候,b进来就无法执行,因为a被阻塞,没执行完。
			Socket s =ss.accept();
			new Thread(new PicServerThraed(s)).start();
		}
	}
}

posted @ 2015-01-25 20:29  静以养身 俭以养德  阅读(150)  评论(0编辑  收藏  举报