和昨天的类似,只是今天学习了文件的传递,主要是加深对socket的理解以及对IO操作中DataInputStream和DataOutputStream类的使用,主要程序代码如下:
服务器端:
package test.net;
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;
/**
* 本例为通过socket编程实现从服务器端发送文件到客户端
* @author zouqingbing
*/
public class fileServer {
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();
}
}
}
客户端:package test.net;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
/**
* 本例使用socket编程实现从服务器端接收程序到客户端
* @author zouqingbing
*/
public class fileClient {
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();
}
}
}
另,要注意的是在socket通讯完毕后要关闭文件和socket连接,这里我起初没有关闭,结果抛出异常,关闭后就ok了.