socket 文件上傳下載

1.建一個java項目作爲客服端

2.建一個wed項目作爲服務器端

3.在TomCat啓動時啓動服務


以下代碼作爲實例,有一些bug請自行調試


//服務器


package com.sky.socket.servce;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
/*
* Tomcat 啓動時就啓動服務
*
*/
public class SocketServlet extends HttpServlet {
/*
  * 構造函數
  */
public SocketServlet() {
  super();
}

/*
  * 初始化
  */
public void init() throws ServletException {
  System.out.println("-----------------開始啓動服務-----------------");
  UploadServce.getInstance().start();
  DownloadServce.getInstance().start();
  System.out.println("-----------------啓動服務成功-----------------");
}
/*
  * 銷燬
  */
public void destroy() {
}
}



//wen.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>socketservce</display-name>
  <servlet>
   <!-- TomCat啓動時啓動服務 -->
   <servlet-name>socketServlet</servlet-name>
  <servlet-class>com.sky.socket.servce.SocketServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
  </servlet>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>



//工具類


package com.sky.socket.client;

import java.net.*;
import java.io.*;
//socket的Util輔助類
public class ClientTools {
private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

int n;

byte b[] = new byte[102400];

public ClientTools(String ip, int port) {
  this.ip = ip;
  this.port = port;
}

/** */
/**
  * 創建socket連接
  *
  * @throws Exception
  *             exception
  */
public boolean CreateConnection() throws Exception {
  boolean falg=false;
  try {
   socket = new Socket(ip, port);
   System.out.println(&quot;連接成功!!!&quot;);
   falg=true;
  } catch (Exception e) {
   e.printStackTrace();
   if (socket != null)
    socket.close();
   throw e;
  
  }
  return falg;
}

/**
  * 往服務器發送數據
  */
public void sendMessage(String sendMessage,InputStream input) throws Exception {
  try {
   out = new DataOutputStream(socket.getOutputStream());
   out.writeUTF(sendMessage);
   if(input!=null){
    while((n=input.read(b,0,8192))!=-1){
     out.write(b,0,n);
    }
    out.flush();
   }
  
  } catch (Exception e) {
   e.printStackTrace();
   if (out != null) {
    out.close();
   }
   throw e;
  } finally {
  }
}
/**
  * 從服務器得到數據流並保存到本地目錄
  */
public boolean getMessageStream(String savePath) throws Exception {
  boolean falg=false;
  String fileName;
  try {
   getMessageStream= new DataInputStream(socket.getInputStream());
   fileName=getMessageStream.readUTF();
   out= new DataOutputStream(new FileOutputStream(new File(savePath+File.separator+fileName)));
   out.writeUTF(fileName);
   while((n=getMessageStream.read(b,0,8192))!=-1){
    out.write(b,0,n);
   }
   out.flush();
   falg=true;
  } catch (Exception e) {
   e.printStackTrace();
   if (getMessageStream != null){
    getMessageStream.close();
    out.close();
   }
   throw e;
  }
  return falg;
}
/**
  * 斷開socket連接
  */
public void shutDownConnection() {
  try {
   if (out != null)
    out.close();
   if (getMessageStream != null)
    getMessageStream.close();
   if (socket != null)
    socket.close();
  } catch (Exception e) {

  }
}
}



//客服端

package com.sky.socket.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
//客服端
public class MyButton extends JFrame {

/**
  * @param args
  */
public JButton send;
public JButton down;
public JPanel panel;

public MyButton() {
  panel = new JPanel();
  panel.setLayout(null);
  this.add(panel);

  send = new JButton(&quot;上傳&quot;);
  send.setBounds(20, 30, 60, 40);
  ButtonEvent butEvent = new ButtonEvent();
  send.addActionListener(butEvent);
  panel.add(send);

  down = new JButton(&quot;下載&quot;);
  down.setBounds(100, 30, 60, 40);
  ButtonDown butDown = new ButtonDown();
  down.addActionListener(butDown);
  panel.add(down);
}
/*
  * 文件上傳
  */
public class ButtonEvent implements ActionListener {
  public void actionPerformed(ActionEvent e4) {
   System.out.println(&quot;-----------文件上傳開始--------------&quot;);
    String ip=&quot;127.0.0.1&quot;;
    int port=8889;
    //創建連接
    ClientTools clientTools=new ClientTools(ip, port);
    try {
    if(clientTools.CreateConnection()){
     //選擇上傳文件
     JFileChooser fileChooser = new JFileChooser();
     int i = fileChooser.showOpenDialog(MyButton.this);// 1表示取消上傳,0確定上傳
     if (i == JFileChooser.APPROVE_OPTION) {
      String filePath = fileChooser.getSelectedFile().getAbsolutePath();
      File file=new File(filePath);
      FileInputStream input = new FileInputStream(file);
      //發送數據
      clientTools.sendMessage(file.getName(), input);
     }
     System.out.println(&quot;------------連接成功-------------&quot;);
     }
    System.out.println(&quot;------------發送數據成功-------------&quot;);
   } catch (Exception e) {
    e.printStackTrace();
   }finally {
    //關閉連接
    System.out.println(&quot;-------------關閉連接-----------&quot;);
    clientTools.shutDownConnection();
   }
   System.out.println(&quot;-----------文件上傳結束--------------&quot;);
  }
}

/*
  * 文件下載
  */
public class ButtonDown implements ActionListener {
  public void actionPerformed(ActionEvent e4) {
   System.out.println(&quot;-----------文件下載開始--------------&quot;);
    String ip=&quot;127.0.0.1&quot;;
    int port=8899;
    //創建連接
    ClientTools clientTools=new ClientTools(ip, port);
    try {
    if(clientTools.CreateConnection()){
     System.out.println(&quot;------------連接成功-------------&quot;);
     //通知服務器我要下載那個文件告訴服務器
     clientTools.sendMessage(&quot;E://2011-08-26//123.txt&quot;, null);
     //選擇保存文件的路徑
     JFileChooser fileChooser = new JFileChooser();
     fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
     int i = fileChooser.showSaveDialog(MyButton.this);// 1表示取消上傳,0確定上傳
     if (i == JFileChooser.APPROVE_OPTION) {
      File file = fileChooser.getSelectedFile();
      // 本地保存路徑,文件名會自動從服務器端繼承而來。
      String savePath = file.getAbsolutePath();
      if(clientTools.getMessageStream(savePath)){
       System.out.println(&quot;下載數據成功&quot;);
      }else{
       System.out.println(&quot;下載數據失敗&quot;);
      }
     }
    
     }
    System.out.println(&quot;------------接收數據成功-------------&quot;);
   } catch (Exception e) {
    e.printStackTrace();
   }finally {
    //關閉連接
    System.out.println(&quot;-------------關閉連接-----------&quot;);
    clientTools.shutDownConnection();
   }
   System.out.println(&quot;-----------文件下載結束--------------&quot;);
  }
}

public static void main(String[] args) {
  MyButton mybtn = new MyButton();
  mybtn.setSize(200, 120);
  mybtn.setVisible(true);
  mybtn.setLocation(300, 220);
  mybtn.setTitle(&quot;socket文件的上傳下載&quot;);
  mybtn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}




//上傳服務器

package com.sky.socket.servce;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
* 和客服端建立練級
*/
public class UploadServce implements Runnable {

private final static int port = 8889;

public static UploadServce uploadservce = null;

public boolean running = false;

protected UploadServce() {
  super();
}

public void start() {
  if (!running) {
   running = true;
   (new Thread(this)).start();
  }
}

/*
  * 實例化
  */
public static UploadServce getInstance() {
  if (uploadservce == null) {
   uploadservce = new UploadServce();
  }
  return uploadservce;
}

public void run() {
  ServerSocket server = null;
  Socket skt = null;
  try {
   server = new ServerSocket(port);
  } catch (IOException ex) {
   System.out.println(&quot;建裏服務器:&quot; + ex.getMessage());
  }
  while (true) {
   try {
    skt = server.accept();
   } catch (IOException ee) {
    System.out.println(&quot;正在等待客戶:&quot; + ee.getMessage());
   }
   if (skt != null)
    new Server_Thread(skt).start();
   else
    continue;
  }

}
}
/*
* 和客戶端進行通信
*/
class Server_Thread extends Thread {

Socket socket = null;

DataInputStream dataInput = null;

DataOutputStream dataOutput=null;

String filename = null;

Server_Thread(Socket skt) {
  socket = skt;
  try {
   /*
    * socket獲取輸入流
    */
   dataInput = new DataInputStream(socket.getInputStream());
  } catch (IOException ex) {
   ex.printStackTrace();
  }
}

public void run() {
  while (true) {
   int n;
   byte b[] = new byte[8192];
   try {//流中讀取文件名  
    filename = dataInput.readUTF();
    SimpleDateFormat sdf=new SimpleDateFormat(&quot;yyyy-MM-dd&quot;); 
    String path=sdf.format(new Date());
    String filePath = &quot;E:&quot;+ File.separator+path;
   
    File file = new File(filePath);
    if (file.exists()) {
     file.delete();
    } else {
     file.mkdirs();
    }
    String fileFullPath = filePath + File.separator + filename;
   
    // 文件路徑
    dataOutput=new DataOutputStream(new FileOutputStream(fileFullPath));
    while ((n = dataInput.read(b, 0, 8192)) != -1) {
     dataOutput.write(b, 0, n);
     System.out.println(&quot;正在上傳數據!!!&quot;);
    }
    System.out.println(&quot;保存的文件路徑爲:&quot;+fileFullPath);
    System.out.println(&quot;寫入完畢!&quot;);
    dataInput.close();
    dataOutput.close();
    socket.close();
    break;
   } catch (Exception ee) {
    break;
   }
  }
}
}




//下載的服務器類

package com.sky.socket.servce;


import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class DownloadServce implements Runnable {

private final static int port = 8899;

public static DownloadServce downloadservce = null;

public boolean running = false;

protected DownloadServce() {
  super();
}

public static DownloadServce getInstance() {
  if (downloadservce == null) {
   downloadservce = new DownloadServce();
  }
  return downloadservce;
}

public void start() {
  if (!running) {
   running = true;
   (new Thread(this)).start();
  }
}
public void run() {
  ServerSocket server = null;
  Socket you = null;
  try {
   server = new ServerSocket(port);
  } catch (IOException ex) {
   System.out.println(&quot;建裏服務器:&quot; + ex.getMessage());
  }
  while (true) {
   try {
    you = server.accept();
   } catch (IOException ee) {
    System.out.println(&quot;正在等待客戶:&quot; + ee.getMessage());
   }
   if (you != null){
    new DownServer_Thread(you).start();
   }else{
    continue;
   }
   
  }

}
}

class DownServer_Thread extends Thread {
Socket socket = null;
DataInputStream in = null;
String filename = null;
DownServer_Thread(Socket c) {
  socket = c;
  try {
   in = new DataInputStream(socket.getInputStream());
  } catch (IOException ex) {
   ex.printStackTrace();
  }
}

public void run() {
  while (true) {
   System.out.println(&quot;建立socket鏈接&quot;);
   //要下載的文件
   DataInputStream dis = null;
   String filename = null;
   DataInputStream fis = null;
   DataOutputStream ps = null;
   // 將文件名及長度傳給客戶端。這裏要真正適用所有平臺,例如中文名的處理,還需要加工,具體可以參見Think In Java
   // 4th裏有現成的代碼。
   try {
    //socket中獲取要下載的文件名
    dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    filename = dis.readUTF();   
    //下載的文件路徑
    String filePath =File.separator+filename;
    System.out.println(&quot;下載文件路徑=================&quot;+filePath);
    File fi = new File(filename);
    //把要下載的文件放入流中
    fis = new DataInputStream(new BufferedInputStream(new FileInputStream(fi)));
    //socket中獲取輸出流
    ps = new DataOutputStream(socket.getOutputStream());
    ps.writeUTF(fi.getName());
    int bufferSize = 8192;//8192
    byte[] buf = new byte[bufferSize];
    int n=0;
    while((n=fis.read(buf,0,8192))!=-1){
     System.out.println(&quot;正在數據...&quot;);
     ps.write(buf,0,n);
    }
    // 注意關閉socket鏈接哦,不然客戶端會等待server的數據過來,
    // 直到socket超時,導致數據不完整。
    ps.close();
    fis.close();
//    dis.close();
//    socket.close();
    System.out.println(&quot;文件傳輸完成&quot;);
    break;   
   } catch (IOException e) {
    e.printStackTrace();
    break;
   } catch (Exception e) {
    e.printStackTrace();
    break;
   } 
  }
 
}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章