服务器端代码:

import java.io.*;
import java.net.*; /**
* Created with IntelliJ IDEA.
* User: HYY
* Date: 13-10-30
* Time: 下午2:15
* To change this template use File | Settings | File Templates.
*/
public class Server { public static void main(String[] args) {
ServerSocket serverSocket;
BufferedInputStream bufferedInputStream;//文件读取流
DataOutputStream dataOutputStream;//向客户端发送的数据流
try {
serverSocket = new ServerSocket(10000);
Socket socket = serverSocket.accept();
System.out.println("客户端连接。");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
bufferedInputStream = new BufferedInputStream(new FileInputStream("c:/temp.sql"));
byte[] buffer = new byte[8192];
int read;
while ((read = bufferedInputStream.read(buffer)) != -1) {
dataOutputStream.write(buffer, 0, read);
dataOutputStream.flush();
}
System.out.println("文件传输完毕!");
bufferedInputStream.close();
dataOutputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
} }
}

客户端代码:

import java.io.*;
import java.net.*; /**
* Created with IntelliJ IDEA.
* User: HYY
* Date: 13-10-30
* Time: 下午2:29
* To change this template use File | Settings | File Templates.
*/
public class Client {
public static void main(String[] args) {
DataInputStream dataInputStream;//从服务器读取数据输入流
FileOutputStream fileOutputStream;//写入本地文件流
try {
Socket socket = new Socket("127.0.0.1", 10000);
System.out.println("连上服务器。");
dataInputStream = new DataInputStream(socket.getInputStream());
File file = new File("d:/temp_copy.sql");
fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[8192];
int read;
while ((read=dataInputStream.read(buffer))>0) {
fileOutputStream.write(buffer, 0, read);
}
System.out.println("文件接收完毕!");
fileOutputStream.close();
dataInputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
05-04 01:28