廢話1000000字省略.........呵呵......
首先是 服務器端:FileServer.java
package com.stars.windsystem.tool.utils;
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;
/**
* @描述: TODO 服務器端: 本例爲通過Socket編程實現從 服務器端 發送文件到 客戶端
* @類名稱: FileServer
* @作者: 宋延軍
* @郵箱: [email protected]
* @日期: Feb 14, 2012 11:57:47 AM
*/
public class FileServer {
/**
* 描述: TODO 服務器端測試入口
* @標題: main
* @設定: @param a
* @返回類型: void
*/
public static void main(String[] a) {
FileServer fileServer = new FileServer();
fileServer.sendFile();
}
public void sendFile() {
byte[] buffer = new byte[1024];// 定義一byte類型的緩衝區。
try {
ServerSocket ssocket = new ServerSocket(2000);
System.out.println("服務器啓動!");
Socket socket = ssocket.accept();
int length = 0;
File f = new File("d:\\aaa.txt");
FileInputStream fis = new FileInputStream(f);
DataInputStream dataIn = new DataInputStream(fis);
DataOutputStream dataOut = new DataOutputStream(socket.getOutputStream());
while ((length = dataIn.read(buffer)) != -1)
{
dataOut.write(buffer, 0, length);
}
dataOut.flush();
dataOut.close();
fis.close();
System.out.println("文件傳送完畢!!!");
socket.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
其次是 客戶端:FileClient.java
package com.stars.windsystem.tool.utils;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
/**
* @描述: TODO 客戶端: 本例使用socket編程實現從服務器端接收程序到客戶端
* @類名稱: FileClient
* @作者: 宋延軍
* @郵箱: [email protected]
* @日期: Feb 14, 2012 12:01:57 PM
*/
public class FileClient {
/**
* 描述: TODO 客戶端測試入口
* @標題: main
* @設定: @param args
* @返回類型: void
*/
public static void main(String[] args) {
FileClient fileClient = new FileClient();
fileClient.receiveFile();
}
public void receiveFile() {
byte[] buffer = new byte[1024];
int length = 0;
try {
Socket socket = new Socket("10.40.2.7", 2000);
DataInputStream dataIn = new DataInputStream(socket
.getInputStream());
File f = new File("d:\\fff.txt");
if (!f.exists())
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
while ((length = dataIn.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
System.out.println("客戶端文件接收完畢!!!");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Over!!!