用JAVA SOCKET发送和接收文件

Java代码   收藏代码
  1. /*服务器端接收文件*/  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.RandomAccessFile;  
  6. import java.net.ServerSocket;  
  7. import java.net.Socket;  
  8.   
  9. import javax.swing.JFileChooser;  
  10.   
  11. /** 
  12. * 该类用到的绑定端口初始为10000,如果绑定不成功则试另外的端口; 
  13. * 绑定次数用tryBindTimes变量,表示如果绑定失败会对它加一; 
  14. * 当前绑定端口由DefaultBindPort+tryBindTimes决定; 
  15. * 外界系统(调用此程序的对象)可以获取当前的帮定端口; 
  16. * 并告诉客户端服务的端口号以使其能正确连接到该端口上; 
  17. * @author 
  18. * 
  19. */  
  20. public class GetFile extends Thread {  
  21.   
  22.     // 服务套接字等待对方的连接和文件发送  
  23.     ServerSocket serSocket;  
  24.     // 由服务套接字产生的 套接字  
  25.     Socket tempSocket;  
  26.     // 用于读取  
  27.     InputStream inSocket;  
  28.     // 随机访问文件  
  29.     RandomAccessFile inFile = null;  
  30.     // 临时缓寸区  
  31.     byte byteBuffer[] = new byte[1024];  
  32.     // 默认用10000端口监听请求  
  33.     int defaultBindPort = 10000;  
  34.     // 初始的绑定端口次数为0  
  35.     int tryBindTimes = 0;  
  36.     // 当前绑定的端口号是10000默认端口  
  37.     int currentBindPort = defaultBindPort + tryBindTimes;  
  38.   
  39.     /** 
  40.     * @构造方法 
  41.     * @抛出异常的原因是无法绑定服务的端口 
  42.     * */  
  43.     public GetFile(int port) throws Exception {  
  44.         try {  
  45.             // 绑定服务的端口  
  46.             this.bindToServerPort();  
  47.   
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.             // 绑定不成功重试  
  51.             System.out.println(e.toString());  
  52.             throw new Exception("绑定端口不成功!");  
  53.   
  54.         }  
  55.         // 文件选择器以当前的目录打开  
  56.         JFileChooser jfc = new JFileChooser(".");  
  57.         jfc.showSaveDialog(new javax.swing.JFrame());  
  58.         // 获取当前的选择文件引用  
  59.         File savedFile = jfc.getSelectedFile();  
  60.   
  61.         // 已经选择了文件  
  62.         if (savedFile != null) {  
  63.             // 读取文件的数据,可以每次以快的方式读取数据  
  64.             inFile = new RandomAccessFile(savedFile, "rw");  
  65.   
  66.         }  
  67.     }  
  68.      
  69.    /** 
  70.     * @监控线程 
  71.     */  
  72.     public void run() {  
  73.         try {  
  74.             if (this.inFile == null) {  
  75.                 System.out.println("没有选择文件");  
  76.                 // 关闭服务方套接字  
  77.                 this.serSocket.close();  
  78.                 // 没有选择文件  
  79.                 return;  
  80.             }  
  81.              
  82.             System.out.println("wait for..." + '\n' + "等待对方接入");  
  83.             // 等待对方的连接  
  84.             tempSocket = serSocket.accept();  
  85.             // 五秒钟连不上将抛出异常  
  86.             this.serSocket.setSoTimeout(5000);  
  87.             // 获取输入流  
  88.             this.inSocket = tempSocket.getInputStream();  
  89.              
  90.         } catch (Exception ex) {  
  91.             System.out.println(ex.toString());  
  92.             ex.printStackTrace();  
  93.             return;  
  94.         }  
  95.          
  96.         // 以下为传送文件代码和 套接字清理工作  
  97.         int amount;  
  98.         try {  
  99.             while ((amount = inSocket.read(byteBuffer)) != -1) {  
  100.                 inFile.write(byteBuffer, 0, amount);  
  101.             }  
  102.             // 关闭流  
  103.             inSocket.close();  
  104.             javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(),  
  105.                     "已接收成功""提示!", javax.swing.JOptionPane.PLAIN_MESSAGE);  
  106.             System.out.println("Get OK");  
  107.             System.out.println("接收完毕!");  
  108.             // 关闭文件  
  109.             inFile.close();  
  110.             // 关闭临时套接字  
  111.             tempSocket.close();  
  112.             // 关闭服务方套接字  
  113.             this.serSocket.close();  
  114.              
  115.         } catch (IOException e) {  
  116.             System.out.println(e.toString());  
  117.             e.printStackTrace();  
  118.         }  
  119.   
  120.     }  
  121.   
  122.     /** 
  123.     * @绑定端口 
  124.     * @throws Exception 抛出异常的原因是无法绑定服务的端口 
  125.     */  
  126.     private void bindToServerPort() throws Exception {  
  127.         try {  
  128.             // 输出绑定的端口号到当前的控制台上  
  129.             System.out.println("试绑定的端口号是:" + this.currentBindPort);  
  130.             // 在自己的机器上开一个服务类套接字并等待发送者的连接  
  131.             serSocket = new ServerSocket(this.currentBindPort);  
  132.   
  133.         } catch (Exception e) {  
  134.             e.printStackTrace();  
  135.             // 绑定不成功重试  
  136.             System.out.println(e.toString());  
  137.             // 试了不止一次了  
  138.             this.tryBindTimes = this.tryBindTimes + 1;  
  139.            // 可查看试的次数getTryBindedTimes  
  140.             this.currentBindPort = this.defaultBindPort + this.tryBindTimes;  
  141.   
  142.             // 如果试的次数超过20次 退出  
  143.             if (this.tryBindTimes >= 20) {  
  144.                 throw new Exception("无法绑定到指定端口" + '\n' + "试了太多次了!");  
  145.   
  146.             }  
  147.             // 递归的绑定  
  148.             this.bindToServerPort();  
  149.         }  
  150.   
  151.         // 输出绑定的端口号到当前的控制台上  
  152.         System.out.println("成功绑定的端口号是: " + this.currentBindPort);  
  153.   
  154.     }  
  155.   
  156.     // 获取试绑定的端口  
  157.     public int getTryBindedTimes() {  
  158.         return this.tryBindTimes;  
  159.     }  
  160.   
  161.     // 获取已经绑定的端口  
  162.     public int getCurrentBindingPort() {  
  163.         return this.currentBindPort;  
  164.     }  
  165.      
  166.   
  167.     /** 
  168.     * @测试方法 
  169.     * @param args 
  170.     */  
  171.     public static void main(String args[]) {  
  172.         GetFile getFile = null;  
  173.         try {  
  174.   
  175.             getFile = new GetFile(10000);  
  176.   
  177.         } catch (Exception e) {  
  178.             e.printStackTrace();  
  179.             System.out.println("无法传送文件!");  
  180.             System.exit(1);  
  181.         }  
  182.         getFile.start();  
  183.   
  184.     }  
  185.   
  186. }  

 

Java代码   收藏代码
  1. /*文件发送端*/  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5. import java.io.RandomAccessFile;  
  6. import java.net.Socket;  
  7.   
  8. import javax.swing.JFileChooser;  
  9.   
  10. /** 
  11. * 在服务器端开启的情况下 实例化套接字 并发送文件 
  12. * 
  13. * @author  
  14. */  
  15. public class SendFile extends Thread {  
  16.   
  17.     // 远程的IP字符串  
  18.     String remoteIPString = null;  
  19.     // 远程的服务端口  
  20.     int port;  
  21.     // 临时套接字  
  22.     Socket tempSocket;  
  23.     // 发送文件用的输出流  
  24.     OutputStream outSocket;  
  25.     // 欲发送的文件  
  26.     RandomAccessFile outFile;  
  27.     // 发送文件用的临时缓存区  
  28.     byte byteBuffer[] = new byte[1024];  
  29.   
  30.     /** 
  31.     * 构造方法仅用于选择发送文件的位置 并从外部接收远程地址和端口 
  32.     * 
  33.     */  
  34.     public SendFile(String remoteIPString, int port) {  
  35.         try {  
  36.             this.remoteIPString = remoteIPString;  
  37.             this.port = port;  
  38.   
  39.            // 选择发送的文件位置  
  40.             JFileChooser jfc = new JFileChooser(".");  
  41.             File file = null;  
  42.             int returnVal = jfc.showOpenDialog(new javax.swing.JFrame());  
  43.             if (returnVal == JFileChooser.APPROVE_OPTION) {  
  44.                 file = jfc.getSelectedFile();  
  45.   
  46.             }  
  47.   
  48.             outFile = new RandomAccessFile(file, "r");  
  49.   
  50.         } catch (Exception e) {  
  51.         }  
  52.     }  
  53.   
  54.     /** 
  55.     * 先决条件是服务器端先开启 
  56.     * 
  57.     */  
  58.     public void run() {  
  59.         try {  
  60.             this.tempSocket = new Socket(this.remoteIPString, this.port);  
  61.             System.out.println("与服务器连接成功!");  
  62.             outSocket = tempSocket.getOutputStream();  
  63.   
  64.             int amount;  
  65.             System.out.println("开始发送文件...");  
  66.             while ((amount = outFile.read(byteBuffer)) != -1) {  
  67.                 outSocket.write(byteBuffer, 0, amount);  
  68.                 System.out.println("文件发送中...");  
  69.             }  
  70.             System.out.println("Send File complete");  
  71.             javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(),  
  72.                     "已发送完毕""提示!", javax.swing.JOptionPane.PLAIN_MESSAGE);  
  73.             outFile.close();  
  74.             tempSocket.close();  
  75.   
  76.         } catch (IOException e) {  
  77.             System.out.println(e.toString());  
  78.             e.printStackTrace();  
  79.         }  
  80.   
  81.     }  
  82.   
  83.     /** 
  84.     * 测试方法 
  85.     * 
  86.     * @param args 
  87.     */  
  88.     public static void main(String args[]) {  
  89.         SendFile sf = new SendFile("127.0.0.1"10000);  
  90.         sf.start();  
  91.   
  92.     }  
  93. }  


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值