使用socket实现局域网中文件数据的简单传输。
public class FileServer {
public static void main(String[] args) {
FileServer fileServer = new FileServer();
fileServer.server();
}
public boolean server() {
try {
//设置serversocket,端口号设置为3336
ServerSocket server = new ServerSocket(3336);
//监听所有访问3336端口的事件
Socket socket = server.accept();
//声明数据输入流,将客户端的数据输入流传入,以便读取数据
DataInputStream inFileName = new DataInputStream(socket.getInputStream());Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("hh点mm分ss秒");
//文件名
String fileName = format.format(date)+inFileName.readUTF();
//传入的文件路径名
String savePath = "D:/"+fileName;System.out.println("文件接收到:"+savePath);
//传入的文件长度
int len = inFileName.readInt();
//文件字符输出流
FileOutputStream outFile = new FileOutputStream(savePath);
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
//遍历流中数据,复制文件
while (true) {int read = 0;
if (inFileName != null) {
read = inFileName.read(buf);
len = read;
}
passedlen += read;
if (read == -1) {
break;
}
System.out.println("文件接收了" + (passedlen * 100 )/len/100 + "%\n");
outFile.write(buf, 0, read);
}
//遍历完成,将需要关闭的流跟socket关闭
outFile.close();socket.close();
server.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
public class FileClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileClient client = new FileClient();
client.send("c:/ex18_3.txt","127.0.0.1",3336);
}
public void send(String file,String path,int num) {
try {
File sendFile = new File(file);
Socket socket = new Socket(path,num);
DataOutputStream out1= new DataOutputStream(socket.getOutputStream());
out1.writeUTF(sendFile.getName());
out1.flush();
out1.writeInt((int) sendFile.length());
out1.flush();
DataInputStream inputStream = new DataInputStream(new FileInputStream(sendFile));
DataOutputStream outFile= new DataOutputStream(socket.getOutputStream());
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
//跟服务器端相同,将文件遍历输入到数据流中
while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
if (read == -1) {
break;
}
outFile.write(buf, 0, read);
}
inputStream.close();
outFile.flush();
//out1.flush();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}