上传图片

/*
上传图片的改进版,服务器通过开启多线程,可以服务多个客户端
同时上传的文件由主函数的参数传入,在服务器端的图片存储路径由ip决定
*/
package picDemo2;
import java.io.*;
import java.net.*;
//客户端
class Client
{
	public static void main(String[] args) throws Exception
	{
		//读入图片并且上传
		Socket s=new Socket("127.0.0.1",10001);
		if(args.length!=1)
		{
			System.out.println("请选择输入的图片");
			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*10)
		{
			System.out.println("文件过大");
			return;
		}
		FileInputStream fis=new FileInputStream(file);
		OutputStream os=s.getOutputStream();
		byte[] out=new byte[1024];
		int len=0;
		while((len=fis.read(out))!=-1)
		{
           os.write(out,0,len);
		}
		s.shutdownOutput();
		InputStream is=s.getInputStream();
		byte[] in=new byte[1024];
		int num=0;
		while((num=is.read(in))!=-1)
		{
			String line=new String(in,0,num);
			System.out.println(line);
		}
		s.close();
		fis.close();
	}
}
//服务器端线程
class ServerThread implements Runnable
{
	private Socket s=null;
	ServerThread(Socket s)
	{
		this.s=s;
	}
   public void run()
   {
	   try
	   {
		int count=1;
        InputStream is=s.getInputStream();
	    String ip=s.getInetAddress().getHostAddress();
	    File file=new File(ip+"("+count+").jpg");
	    while(file.exists())
		 file=new File(ip+"("+(count++)+").jpg");
	    FileOutputStream fos=new FileOutputStream(file);
	    byte[] out=new byte[1024];
	    int len=0;
	   while((len=is.read(out))!=-1)
	   {
          fos.write(out,0,len);
	   }
	    OutputStream os=s.getOutputStream();
	    os.write("上传成功".getBytes());
		s.close();
		fos.close();
       }
	   catch (Exception e)
	   {
	   }
   }
}
//服务器端
class Server
{
	public static void main(String args[]) throws Exception
	{
	ServerSocket ss=new ServerSocket(10001);
	while(true)
	{
	Socket s=ss.accept();
	new Thread(new ServerThread(s)).start();
	}
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值