客户端代码
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
/**
* 使用TCP协议实现上传功能的客户端
*/
public class UploadClient {
/**
* 测试方法,将C:/1.txt 文件上传到服务器D:/2.txt位置
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
String localFilePath = "C:\\1.txt"; //本地文件
String serverFilePath = "D:\\2.txt"; //保存在服务器中的文件名称
String host = "127.0.0.1"; //服务器地址
int port = 22222; //服务器端口
UploadClient.upload(localFilePath, serverFilePath, host, port);
long end = System.currentTimeMillis();
System.out.println((end - start) / 1000.0);
}
/**
* 上传文件到服务器
*
* @param localFilePath 本地上传文件名称
* @param serverFilePath 服务器保存文件名称
* @param host 服务器ip
* @param port 服务器端口
*/
private static void upload(String localFilePath, String serverFilePath, String host, int port) throws IOException {
Socket socket = new Socket(host, port);
OutputStream out = socket.getOutputStream();
byte[] buf = new byte[1024];
//业务逻辑
out.write(serverFilePath.getBytes());
out.write('\n');
FileInputStream fis = new FileInputStream(localFilePath);//2.写入文件内容
int len;
while ((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.flush();
fis.close();//关闭
out.close();
}
}
服务端代码
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
/**
* 使用TCP协议实现上传功能的服务器端
* 接收到客户端上传任务,开启一个线程获取客户端上传的文件
*/
public class UploadServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(22222);
while (true) {
System.out.println("等待连接……");//可以同时获取多个客户端数据
Socket transSocket = serverSocket.accept();//阻塞,客户端请求上传之后,数据都在transSocket里面
save(transSocket);//处理数据transSocket之后关闭连接
transSocket.close();//关闭客户端连接
}
//serverSocket.close();//关闭连接
}
/**
* 将transSocket中的数据保存到服务器中
*
* @param transSocket
*/
public static void save(Socket transSocket) throws IOException {
InputStream in = transSocket.getInputStream();
//第一步:获取文件名,构造文件输出流
ArrayList<Integer> al = new ArrayList<>();
int ch;
while ((ch = in.read()) != '\n') {//第一行保存的文件名称
al.add(ch);
}
char[] nameArr = new char[al.size()];
for (int i = 0; i < al.size(); i++) {
int j = al.get(i);
nameArr[i] = (char) j;
}
String name = new String(nameArr);
OutputStream out = new FileOutputStream(name);
//第二步:将输入流中的其他内容写入到文件
byte[] buf = new byte[102400];//设置缓存大小
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.flush();//刷新内存中没有刷新到服务器的数据到服务器中
in.close();
out.close();
}
}