首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

socket 文件下传上载

2012-12-18 
socket 文件上传下载1.建一个java项目作为客服端 2.建一个wed项目作为服务器端 3.在TomCat启动时启动服务

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;
?? }?
? }
?
}
}

?

热点排行