day24/TcpThreadCopyPic.java

来源:互联网 发布:python while循环游戏 编辑:程序博客网 时间:2024/05/16 18:16
/*客户端并发上传图片到服务端*/import java.io.*;import java.net.*;//客户端class TcpClient1 {public static void main(String[] args) throws Exception{//---------------------对上传的图片做判断-------------if(args.length!=1){System.out.println("请选择一个bmp格式的图片");return ;}File file = new File(args[0]);if(!(file.exists()&&file.isFile())){System.out.println("该文件有问题,要么不存在,要么不是文件");return ;}if(!(file.getName().endsWith(".bmp"))){System.out.println("图片格式错误");return ;}if(file.length()>1024*1024*5){System.out.println("文件过大,没安好心");return ;}//-----------------------------------------------------Socket s = new Socket("192.168.1.100",9999);FileInputStream fs = new FileInputStream(file);OutputStream out = s.getOutputStream();byte[] buf = new byte[1024];int len=0;while((len=fs.read(buf))!=-1){out.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));fs.close();s.close();}}/*服务端这个服务端有个局限性。当A客户端连接上以后,被服务端获取到,服务端执行具体流程。这时B客户端连接,B只有等待。因为服务端还没有处理完A客户端的请求,还没有循环回来执行下次accept方法。所以暂时获取不到B客户端对象。那么为了可以让多个客户端同时并发访问服务端。那么服务端最好就是将每个客户端封装到一个单独的线程中。这样就可以同时处理多个客户端的请求。如何定义线程呢?只要明确了每一个客户端要在服务端执行的代码即可。将该代码存入run方法中。*/class TcpServer1{public static void main(String[] args) throws Exception{ServerSocket ss = new ServerSocket(9999);while(true){Socket s = ss.accept();new Thread(new MultiThreadClient(s)).start();}}}//服务端开启的线程。//客户端向服务端发一个请求,服务端就开一个线程去处理该客户端class MultiThreadClient implements Runnable{private Socket s;MultiThreadClient(Socket s){this.s=s;}public void run(){int count=1;String ip = s.getInetAddress().getHostAddress();try{System.out.println(ip+"...connected");//----------上传后判断文件在本地是否存在,存在就加1保存File file = new File(ip+"("+count+")"+".bmp");while(file.exists())file=new File(ip+"("+(count++)+")"+".bmp");//--------------------InputStream is = s.getInputStream();FileOutputStream fs = new FileOutputStream(file);byte[] buf = new byte[1024];int len=0;while((len=is.read(buf))!=-1){fs.write(buf,0,len);}OutputStream out = s.getOutputStream();out.write("上传成功".getBytes());fs.close();s.close();}catch (Exception e){throw new RuntimeException(ip+"上传失败");}}}

0 0