Java基于Socket文件传输示例

来源:互联网 发布:致远软件招聘 编辑:程序博客网 时间:2024/05/22 13:56
需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步的了解。在一位网友提供的程序基础上,俺进行了一些加工,采用了缓冲输入/输出流来包装输出流,再采用数据输入/输出输出流进行包装,加快传输的速度。废话少说,先来看服务器端的程序。

1.服务器端

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import  java.io.BufferedInputStream;  
  2. import  java.io.DataInputStream;  
  3. import  java.io.DataOutputStream;  
  4. import  java.io.File;  
  5. import  java.io.FileInputStream;  
  6. import  java.net.ServerSocket;  
  7. import  java.net.Socket;  
  8.   
  9. public   class  ServerTest  {  
  10.      int  port  =   8821 ;  
  11.   
  12.      void  start()  {  
  13.         Socket s  =   null ;  
  14.          try   {  
  15.             ServerSocket ss  =   new  ServerSocket(port);  
  16.              while  ( true )  {  
  17.                  //  选择进行传输的文件  
  18.                 String filePath  =   " D://lib.rar " ;  
  19.                 File fi  =   new  File(filePath);  
  20.   
  21.                 System.out.println( " 文件长度: "   +  ( int ) fi.length());  
  22.   
  23.                  //  public Socket accept() throws  
  24.                  //  IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。  
  25.   
  26.                 s  =  ss.accept();  
  27.                 System.out.println( " 建立socket链接 " );  
  28.                 DataInputStream dis  =   new  DataInputStream( new  BufferedInputStream(s.getInputStream()));  
  29.                 dis.readByte();  
  30.   
  31.                 DataInputStream fis  =   new  DataInputStream( new  BufferedInputStream( new  FileInputStream(filePath)));  
  32.                 DataOutputStream ps  =   new  DataOutputStream(s.getOutputStream());  
  33.                  // 将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。  
  34.                 ps.writeUTF(fi.getName());  
  35.                 ps.flush();  
  36.                 ps.writeLong(( long ) fi.length());  
  37.                 ps.flush();  
  38.   
  39.                  int  bufferSize  =   8192 ;  
  40.                  byte [] buf  =   new   byte [bufferSize];  
  41.   
  42.                  while  ( true )  {  
  43.                      int  read  =   0 ;  
  44.                      if  (fis  !=   null )  {  
  45.                         read  =  fis.read(buf);  
  46.                     }  
  47.   
  48.                      if  (read  ==   - 1 )  {  
  49.                          break ;  
  50.                     }  
  51.                     ps.write(buf,  0 , read);  
  52.                 }  
  53.                 ps.flush();  
  54.                  //  注意关闭socket链接哦,不然客户端会等待server的数据过来,  
  55.                  //  直到socket超时,导致数据不完整。                  
  56.                 fis.close();  
  57.                 s.close();                  
  58.                 System.out.println( " 文件传输完成 " );  
  59.             }  
  60.   
  61.         }   catch  (Exception e)  {  
  62.             e.printStackTrace();  
  63.         }  
  64.     }  
  65.   
  66.      public   static   void  main(String arg[])  {  
  67.          new  ServerTest().start();  
  68.     }  
  69. }  

2.socket的Util辅助类

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1.  import  java.net. * ;  
  2. import  java.io. * ;  
  3.   
  4. public   class  ClientSocket  {  
  5.      private  String ip;  
  6.   
  7.      private   int  port;  
  8.   
  9.      private  Socket socket  =   null ;  
  10.   
  11.     DataOutputStream out  =   null ;  
  12.   
  13.     DataInputStream getMessageStream  =   null ;  
  14.   
  15.      public  ClientSocket(String ip,  int  port)  {  
  16.          this .ip  =  ip;  
  17.          this .port  =  port;  
  18.     }  
  19.   
  20.      /** 
  21.      * 创建socket连接 
  22.      *  
  23.      *  @throws  Exception 
  24.      *             exception 
  25.       */  
  26.      public   void  CreateConnection()  throws  Exception  {  
  27.          try   {  
  28.             socket  =   new  Socket(ip, port);  
  29.         }   catch  (Exception e)  {  
  30.             e.printStackTrace();  
  31.              if  (socket  !=   null )  
  32.                 socket.close();  
  33.              throw  e;  
  34.         }   finally   {  
  35.         }  
  36.     }  
  37.   
  38.      public   void  sendMessage(String sendMessage)  throws  Exception  {  
  39.          try   {  
  40.             out  =   new  DataOutputStream(socket.getOutputStream());  
  41.              if  (sendMessage.equals( " Windows " ))  {  
  42.                 out.writeByte( 0x1 );  
  43.                 out.flush();  
  44.                  return ;  
  45.             }  
  46.              if  (sendMessage.equals( " Unix " ))  {  
  47.                 out.writeByte( 0x2 );  
  48.                 out.flush();  
  49.                  return ;  
  50.             }  
  51.              if  (sendMessage.equals( " Linux " ))  {  
  52.                 out.writeByte( 0x3 );  
  53.                 out.flush();  
  54.             }   else   {  
  55.                 out.writeUTF(sendMessage);  
  56.                 out.flush();  
  57.             }  
  58.         }   catch  (Exception e)  {  
  59.             e.printStackTrace();  
  60.              if  (out  !=   null )  
  61.                 out.close();  
  62.              throw  e;  
  63.         }   finally   {  
  64.         }  
  65.     }  
  66.   
  67.      public  DataInputStream getMessageStream()  throws  Exception  {  
  68.          try   {  
  69.             getMessageStream  =   new  DataInputStream( new  BufferedInputStream(socket.getInputStream()));  
  70.              return  getMessageStream;  
  71.         }   catch  (Exception e)  {  
  72.             e.printStackTrace();  
  73.              if  (getMessageStream  !=   null )  
  74.                 getMessageStream.close();  
  75.              throw  e;  
  76.         }   finally   {  
  77.         }  
  78.     }  
  79.   
  80.      public   void  shutDownConnection()  {  
  81.          try   {  
  82.              if  (out  !=   null )  
  83.                 out.close();  
  84.              if  (getMessageStream  !=   null )  
  85.                 getMessageStream.close();  
  86.              if  (socket  !=   null )  
  87.                 socket.close();  
  88.         }   catch  (Exception e)  {  
  89.   
  90.         }  
  91.     }  
  92. }  

3.客户端

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1.  import  java.io.BufferedOutputStream;  
  2. import  java.io.DataInputStream;  
  3. import  java.io.DataOutputStream;  
  4. import  java.io.FileOutputStream;  
  5.   
  6. public   class  ClientTest  {  
  7.      private  ClientSocket cs  =   null ;  
  8.   
  9.      private  String ip  =   " localhost " ; //  设置成服务器IP  
  10.   
  11.      private   int  port  =   8821 ;  
  12.   
  13.      private  String sendMessage  =   " Windwos " ;  
  14.   
  15.      public  ClientTest()  {  
  16.          try   {  
  17.              if  (createConnection())  {  
  18.                 sendMessage();  
  19.                 getMessage();  
  20.             }  
  21.   
  22.         }   catch  (Exception ex)  {  
  23.             ex.printStackTrace();  
  24.         }  
  25.     }  
  26.   
  27.      private   boolean  createConnection()  {  
  28.         cs  =   new  ClientSocket(ip, port);  
  29.          try   {  
  30.             cs.CreateConnection();  
  31.             System.out.print( " 连接服务器成功! "   +   " /n " );  
  32.              return   true ;  
  33.         }   catch  (Exception e)  {  
  34.             System.out.print( " 连接服务器失败! "   +   " /n " );  
  35.              return   false ;  
  36.         }  
  37.   
  38.     }  
  39.   
  40.      private   void  sendMessage()  {  
  41.          if  (cs  ==   null )  
  42.              return ;  
  43.          try   {  
  44.             cs.sendMessage(sendMessage);  
  45.         }   catch  (Exception e)  {  
  46.             System.out.print( " 发送消息失败! "   +   " /n " );  
  47.         }  
  48.     }  
  49.   
  50.      private   void  getMessage()  {  
  51.          if  (cs  ==   null )  
  52.              return ;  
  53.         DataInputStream inputStream  =   null ;  
  54.          try   {  
  55.             inputStream  =  cs.getMessageStream();  
  56.         }   catch  (Exception e)  {  
  57.             System.out.print( " 接收消息缓存错误/n " );  
  58.              return ;  
  59.         }  
  60.   
  61.          try   {  
  62.              // 本地保存路径,文件名会自动从服务器端继承而来。  
  63.             String savePath  =   " E:// " ;  
  64.              int  bufferSize  =   8192 ;  
  65.              byte [] buf  =   new   byte [bufferSize];  
  66.              int  passedlen  =   0 ;  
  67.              long  len = 0 ;  
  68.               
  69.             savePath  +=  inputStream.readUTF();  
  70.             DataOutputStream fileOut  =   new  DataOutputStream( new  BufferedOutputStream( new  BufferedOutputStream( new  FileOutputStream(savePath))));  
  71.             len  =  inputStream.readLong();  
  72.               
  73.             System.out.println( " 文件的长度为: "   +  len  +   " /n " );  
  74.             System.out.println( " 开始接收文件! "   +   " /n " );  
  75.                       
  76.              while  ( true )  {  
  77.                  int  read  =   0 ;  
  78.                  if  (inputStream  !=   null )  {  
  79.                     read  =  inputStream.read(buf);  
  80.                 }  
  81.                 passedlen  +=  read;  
  82.                  if  (read  ==   - 1 )  {  
  83.                      break ;  
  84.                 }  
  85.                  // 下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比  
  86.                 System.out.println( " 文件接收了 "   +   (passedlen  *   100 /  len)  +   " %/n " );  
  87.                 fileOut.write(buf,  0 , read);  
  88.             }  
  89.             System.out.println( " 接收完成,文件存为 "   +  savePath  +   " /n " );  
  90.   
  91.             fileOut.close();  
  92.         }   catch  (Exception e)  {  
  93.             System.out.println( " 接收消息错误 "   +   " /n " );  
  94.              return ;  
  95.         }  
  96.     }  
  97.   
  98.      public   static   void  main(String arg[])  {  
  99.          new  ClientTest();  
  100.     }  
  101. }   

这就实现了从服务器端向客户端发送文件的过程,当然,反过来,也一样.稍有不同.代码中对跨平台的细节没有实现,


转自【http://www.open-open.com/lib/view/open1390525710507.html】

0 0
原创粉丝点击