java socket文件传输

来源:互联网 发布:大数据存储技术研究 编辑:程序博客网 时间:2024/05/16 14:42
  1. package com.socket.sample;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.DataInputStream;  
  5. import java.io.DataOutputStream;  
  6. import java.io.File;  
  7. import java.io.FileInputStream;  
  8. import java.net.ServerSocket;  
  9. import java.net.Socket;  
  10.   
  11. public class ServerTest {  
  12.     int port = 8821;  
  13.   
  14.     void start() {  
  15.         Socket s = null;  
  16.         try {  
  17.             ServerSocket ss = new ServerSocket(port);  
  18.             while (true) {  
  19.                 // 选择进行传输的文件  
  20.                 String filePath = "D:\\lib.rar";  
  21.                 File fi = new File(filePath);  
  22.   
  23.                 System.out.println("文件长度:" + (int) fi.length());  
  24.   
  25.                 // public Socket accept() throws  
  26.                 // IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。  
  27.   
  28.                 s = ss.accept();  
  29.                 System.out.println("建立socket链接");  
  30.                 DataInputStream dis = new DataInputStream(  
  31.                         new BufferedInputStream(s.getInputStream()));  
  32.                 dis.readByte();  
  33.   
  34.                 DataInputStream fis = new DataInputStream(  
  35.                         new BufferedInputStream(new FileInputStream(filePath)));  
  36.                 DataOutputStream ps = new DataOutputStream(s.getOutputStream());  
  37.                 // 将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java  
  38.                 // 4th里有现成的代码。  
  39.                 ps.writeUTF(fi.getName());  
  40.                 ps.flush();  
  41.                 ps.writeLong((long) fi.length());  
  42.                 ps.flush();  
  43.   
  44.                 int bufferSize = 8192;  
  45.                 byte[] buf = new byte[bufferSize];  
  46.   
  47.                 while (true) {  
  48.                     int read = 0;  
  49.                     if (fis != null) {  
  50.                         read = fis.read(buf);  
  51.                         // 从包含的输入流中读取一定数量的字节,并将它们存储到缓冲区数组 b  
  52.                         // 中。以整数形式返回实际读取的字节数。在输入数据可用、检测到文件末尾 (end of file)  
  53.                         // 或抛出异常之前,此方法将一直阻塞。  
  54.                     }  
  55.   
  56.                     if (read == -1) {  
  57.                         break;  
  58.                     }  
  59.                     ps.write(buf, 0, read);  
  60.                 }  
  61.                 ps.flush();  
  62.                 // 注意关闭socket链接哦,不然客户端会等待server的数据过来,  
  63.                 // 直到socket超时,导致数据不完整。  
  64.                 fis.close();  
  65.                 s.close();  
  66.                 System.out.println("文件传输完成");  
  67.             }  
  68.   
  69.         } catch (Exception e) {  
  70.             e.printStackTrace();  
  71.         }  
  72.     }  
  73.   
  74.     public static void main(String arg[]) {  
  75.         new ServerTest().start();  
  76.     }  
  77. }  

客户端工具(SocketTool)

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


客户端(Client)

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