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("連接成功!!!");
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("上傳");
send.setBounds(20, 30, 60, 40);
ButtonEvent butEvent = new ButtonEvent();
send.addActionListener(butEvent);
panel.add(send);
down = new JButton("下載");
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("-----------文件上傳開始--------------");
String ip="127.0.0.1";
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("------------連接成功-------------");
}
System.out.println("------------發送數據成功-------------");
} catch (Exception e) {
e.printStackTrace();
}finally {
//關閉連接
System.out.println("-------------關閉連接-----------");
clientTools.shutDownConnection();
}
System.out.println("-----------文件上傳結束--------------");
}
}
/*
* 文件下載
*/
public class ButtonDown implements ActionListener {
public void actionPerformed(ActionEvent e4) {
System.out.println("-----------文件下載開始--------------");
String ip="127.0.0.1";
int port=8899;
//創建連接
ClientTools clientTools=new ClientTools(ip, port);
try {
if(clientTools.CreateConnection()){
System.out.println("------------連接成功-------------");
//通知服務器我要下載那個文件告訴服務器
clientTools.sendMessage("E://2011-08-26//123.txt", 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("下載數據成功");
}else{
System.out.println("下載數據失敗");
}
}
}
System.out.println("------------接收數據成功-------------");
} catch (Exception e) {
e.printStackTrace();
}finally {
//關閉連接
System.out.println("-------------關閉連接-----------");
clientTools.shutDownConnection();
}
System.out.println("-----------文件下載結束--------------");
}
}
public static void main(String[] args) {
MyButton mybtn = new MyButton();
mybtn.setSize(200, 120);
mybtn.setVisible(true);
mybtn.setLocation(300, 220);
mybtn.setTitle("socket文件的上傳下載");
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("建裏服務器:" + ex.getMessage());
}
while (true) {
try {
skt = server.accept();
} catch (IOException ee) {
System.out.println("正在等待客戶:" + 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("yyyy-MM-dd");
String path=sdf.format(new Date());
String filePath = "E:"+ 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("正在上傳數據!!!");
}
System.out.println("保存的文件路徑爲:"+fileFullPath);
System.out.println("寫入完畢!");
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("建裏服務器:" + ex.getMessage());
}
while (true) {
try {
you = server.accept();
} catch (IOException ee) {
System.out.println("正在等待客戶:" + 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("建立socket鏈接");
//要下載的文件
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("下載文件路徑================="+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("正在數據...");
ps.write(buf,0,n);
}
// 注意關閉socket鏈接哦,不然客戶端會等待server的數據過來,
// 直到socket超時,導致數據不完整。
ps.close();
fis.close();
// dis.close();
// socket.close();
System.out.println("文件傳輸完成");
break;
} catch (IOException e) {
e.printStackTrace();
break;
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
}