版权声明:本文为博主原创文章,转载请说明出处,谢谢。 https://blog.csdn.net/qq_27070443/article/details/61621084
服务端
package me.mxzf;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @Title: FileServer
* @Dscription: 文件服务器
* @author Deleter
* @date 2017年3月12日 下午4:22:54
* @version 1.0
*/
public class FileServer {
public static void main(String[] args) {
int len;
String fileName;
FileOutputStream fos;
try {
ServerSocket serverSocket = new ServerSocket(1234);
Socket socket = serverSocket.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(
socket.getOutputStream());
// 读取文件名
fileName = dis.readUTF();
System.out.println(fileName);
// 读取文件长度
len = dis.readInt();
System.out.println(len);
// 读取文件内容
byte[] buff = new byte[len];
dis.read(buff);
// 写出文件
fos = new FileOutputStream("D:/" + fileName);
fos.write(buff);
fos.close();
// 反馈客户端,传输结果
dos.writeUTF("传输完成");
dos.flush();
// 传输完成之后一定记住close掉
// 不然客户端会等待server的数据过来
// 直到socket超时,导致数据不完整
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端
package me.mxzf;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
/**
*
* @Title: FileClient
* @Dscription: 客户端
* @author Deleter
* @date 2017年3月12日 下午4:23:15
* @version 1.0
*/
public class FileClient {
public static void main(String[] args) {
try {
Socket socket = new Socket(InetAddress.getLocalHost(), 1234);
DataOutputStream dos = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
File file = new File("c:/DB.zip");
// 上传文件名
dos.writeUTF(file.getName());
dos.flush();
// 获取文件长度
FileInputStream fis = new FileInputStream(file);
int len = fis.available();
dos.writeInt(len);
dos.flush();
// 文件内容
byte[] buff = new byte[len];
dos.write(fis.read(buff));
dos.flush();
// 关闭文件流
fis.close();
// 读取服务器反馈信息
String content = dis.readUTF();
dis.close();
// 打印输出
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
多线程多客户端文件传输就是:循环+线程+管理类
感觉比较麻烦的话,可以直接用对象流,但是为了让初学者能够更好的理解这些比较乏味的东西,还是要多敲代码,虽然这种代码的确有些不堪入目,哎呀哎呀,得。