当前位置: 移动技术网 > IT编程>开发语言>Java > 浅析Java基于Socket的文件传输案例

浅析Java基于Socket的文件传输案例

2019年07月22日  | 移动技术网IT编程  | 我要评论
本文实例介绍了java基于socket的文件传输案例,分享给大家供大家参考,具体内容如下 1、java代码 package com.wf.demo.sock

本文实例介绍了java基于socket的文件传输案例,分享给大家供大家参考,具体内容如下

1、java代码

package com.wf.demo.socket.socketfile; 
 
import java.net.*; 
import java.io.*; 
 
/** 
 * 2.socket的util辅助类 
 * 
 * @author willson 
 * 
 */ 
public class clientsocket { 
 
  private string ip; 
 
  private int port; 
 
  private socket socket = null; 
 
  dataoutputstream out = null; 
 
  datainputstream getmessagestream = null; 
 
  public clientsocket(string ip, int port) { 
    this.ip = ip; 
    this.port = port; 
  } 
 
  /** 
   * 创建socket连接 
   * 
   * @throws exception 
   *       exception 
   */ 
  public void createconnection() throws exception { 
 
    try { 
      socket = new socket(ip, port); 
    } catch (exception e) { 
      e.printstacktrace(); 
      if (socket != null) 
        socket.close(); 
      throw e; 
    } finally { 
    } 
  } 
 
  // 发送消息 
  public void sendmessage(string sendmessage) throws exception { 
    try { 
      out = new dataoutputstream(socket.getoutputstream()); 
      if (sendmessage.equals("windows")) { 
        out.writebyte(0x1); 
        out.flush(); 
        return; 
      } 
      if (sendmessage.equals("unix")) { 
        out.writebyte(0x2); 
        out.flush(); 
        return; 
      } 
      if (sendmessage.equals("linux")) { 
        out.writebyte(0x3); 
        out.flush(); 
      } else { 
        out.writeutf(sendmessage); 
        out.flush(); 
      } 
    } catch (exception e) { 
      e.printstacktrace(); 
      if (out != null) 
        out.close(); 
      throw e; 
    } finally { 
    } 
  } 
 
  // 接受消息 
  public datainputstream getmessagestream() throws exception { 
    try { 
      getmessagestream = new datainputstream(new bufferedinputstream( 
          socket.getinputstream())); 
      return getmessagestream; 
    } catch (exception e) { 
      e.printstacktrace(); 
      if (getmessagestream != null) 
        getmessagestream.close(); 
      throw e; 
    } finally { 
    } 
  } 
 
  // 关闭连接 
  public void shutdownconnection() { 
    try { 
      if (out != null) 
        out.close(); 
      if (getmessagestream != null) 
        getmessagestream.close(); 
      if (socket != null) 
        socket.close(); 
    } catch (exception e) { 
    } 
  } 
} 

2、java代码

package com.wf.demo.socket.socketfile; 
 
import java.io.bufferedinputstream; 
import java.io.datainputstream; 
import java.io.dataoutputstream; 
import java.io.file; 
import java.io.fileinputstream; 
import java.net.serversocket; 
import java.net.socket; 
 
/** 
 * 1.服务器端 
 * 
 * @author willson 
 * 
 */ 
public class servertest { 
   
  int port = 8821; 
 
  void start() { 
     
    socket socket = null; 
     
    try { 
       
      serversocket serversocket = new serversocket(port); 
       
      while (true) { 
        // 选择进行传输的文件 
        string filepath = "e:\\lib.zip"; 
         
        file fi = new file(filepath); 
 
        system.out.println("file name:" + fi.getname() + ";\tfile size():" + (int) fi.length() + "bytes"); 
 
        // public socket accept() throws 
        // ioexception侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。 
 
         
        system.out.println("等待客户端连接,连接端口:" + port); 
        socket = serversocket.accept(); 
         
        system.out.println("建立socket链接"); 
         
        datainputstream dis = new datainputstream(new bufferedinputstream(socket.getinputstream())); 
         
        dis.readbyte(); 
 
        datainputstream fis = new datainputstream(new bufferedinputstream(new fileinputstream(filepath))); 
         
        dataoutputstream ps = new dataoutputstream(socket.getoutputstream()); 
         
        // 将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见think in java 
        // 4th里有现成的代码。 
        ps.writeutf(fi.getname()); 
        ps.flush(); 
        ps.writelong((long) fi.length()); 
        ps.flush(); 
 
        int buffersize = 8192; 
        byte[] buf = new byte[buffersize]; 
 
        while (true) { 
           
          int read = 0; 
          if (fis != null) { 
            read = fis.read(buf); 
          } 
 
          if (read == -1) { 
            break; 
          } 
          ps.write(buf, 0, read); 
        } 
         
        ps.flush(); 
        // 注意关闭socket链接哦,不然客户端会等待server的数据过来, 
        // 直到socket超时,导致数据不完整。 
        fis.close(); 
        socket.close(); 
         
        system.out.println("文件传输完成\n"); 
      } 
 
    } catch (exception e) { 
      e.printstacktrace(); 
    } 
  } 
 
  public static void main(string arg[]) { 
    new servertest().start(); 
  } 
} 
 
 


3、客户端

package com.wf.demo.socket.socketfile; 
 
import java.io.bufferedoutputstream; 
import java.io.datainputstream; 
import java.io.dataoutputstream; 
import java.io.fileoutputstream; 
 
/** 
 * 3.客户端 
 * 
 * @author willson 
 * 
 */ 
public class clienttest { 
 
  private clientsocket cs = null; 
 
  private string ip = "localhost";// 设置成服务器ip 
 
  private int port = 8821; 
 
  private string sendmessage = "windwos"; 
 
  public clienttest() { 
 
    try { 
      if (createconnection()) { 
        sendmessage(); 
        getmessage("f:\\"); 
      } 
    } catch (exception ex) { 
      ex.printstacktrace(); 
    } 
  } 
 
  private boolean createconnection() { 
     
    cs = new clientsocket(ip, port); 
    try { 
      cs.createconnection(); 
      system.out.print("连接服务器成功!" + "\n"); 
      return true; 
    } catch (exception e) { 
      system.out.print("连接服务器失败!" + "\n"); 
      return false; 
    } 
 
  } 
 
  private void sendmessage() { 
     
    if (cs == null) 
      return; 
    try { 
      cs.sendmessage(sendmessage); 
    } catch (exception e) { 
      system.out.print("发送消息失败!" + "\n"); 
    } 
  } 
 
  private void getmessage(string savepath) { 
     
    if (cs == null) 
      return; 
    datainputstream inputstream = null; 
    try { 
      inputstream = cs.getmessagestream(); 
    } catch (exception e) { 
      system.out.print("接收消息缓存错误\n"); 
      return; 
    } 
 
    try { 
       
      // 本地保存路径,文件名会自动从服务器端继承而来。 
      int buffersize = 8192; 
      byte[] buf = new byte[buffersize]; 
      int passedlen = 0; 
      long len = 0; 
 
      savepath += inputstream.readutf(); 
      dataoutputstream fileout = new dataoutputstream(new bufferedoutputstream(new bufferedoutputstream(new fileoutputstream(savepath)))); 
      len = inputstream.readlong(); 
 
      system.out.println("file size():" + len + "bytes"); 
      system.out.println("开始接收文件!" + "\n"); 
 
      while (true) { 
         
        int read = 0; 
        if (inputstream != null) { 
          read = inputstream.read(buf); 
        } 
        passedlen += read; 
        if (read == -1) { 
          break; 
        } 
        // 下面进度条本为图形界面的prograssbar做的,这里如果是打文件,可能会重复打印出一些相同的百分比 
        system.out.println("文件接收了" + (passedlen * 100 / len) + "%\n"); 
        fileout.write(buf, 0, read); 
      } 
      system.out.println("接收完成,文件存为" + savepath + "\n"); 
 
      fileout.close(); 
    } catch (exception e) { 
      system.out.println("接收消息错误" + "\n"); 
      return; 
    } 
  } 
 
  public static void main(string arg[]) { 
    new clienttest(); 
  } 
} 

希望本文所述对大家学习java程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网