Java基于Socket文件传输示例 --- (http://www.blogjava.net/sterning/archive/2007/10/13/152508.html)

最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步的了解。在一位网友提供的程序基础上,俺进行了一些加工,采用了缓冲输入/输出流来包装输出流,再采用数据输入/输出输出流进行包装,加快传输的速度。废话少说,先来看服务器端的程序。

1.服务器端

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

2.socket的Util辅助类

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

3.客户端

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

这就实现了从服务器端向客户端发送文件的过程,当然,反过来,也一样.稍有不同.代码中对跨平台的细节没有实现,有时间或兴趣的朋友可以提供一下.

<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值