多客户端文件上传
程序员文章站
2024-03-23 09:48:28
...
多客户端文件上传
先启动
ThreadServer再启动client
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
/**
* @author blue
* @date 2020年8月16日
*/
public static void main(String[] args) throws Exception {
//1、创建客户端socket
Socket socket = new Socket("localhost", 8080);
//2、读取客户端要上传的图片
FileInputStream bfi = new FileInputStream( "E:\\test.JPG");//这里是要上传文件的路径
//3、获取socket输出流,将读到的图片数据发给服务端
OutputStream outputStream =socket.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
//使用输出流写出图片数据
while ((len = bfi.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
// 发送完毕客户端停止读取
socket.shutdownOutput();
//读取服务端返回的数据
InputStream inputStream = socket.getInputStream();
//设置缓存空间这里可以用buffer....
byte[] bufIn = new byte[1024];
int lenIn = inputStream.read(buf);
String text = new String(buf, 0, lenIn);
System.out.println(text);
//关闭资源
bfi.close();
socket.close();
}
}
核心在于用while()将service处于一直启动的状态
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ThreadServer {
/**
* @author blue
* @date 2020年8月16日
*/
public static void main(String[] args) throws IOException {
//创建TCP的socket服务端
ServerSocket ssc =new ServerSocket(8080);
while (true){
//获取客户端
//阻塞式方法,有客户端连接就开启,否则一直处于等待状态
Socket socket = ssc.accept();
new Thread(new UploadThread(socket)).start();
}
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class UploadThread implements Runnable {
// 规定上传文件的最大大小
private static final int SIZE = 1024 * 1024 * 20;// 这里规定的是不能上传超过20m的文件
private Socket socket;
public UploadThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
int count = 0;
String ip = socket.getInetAddress().getHostAddress();
System.out.println(ip + "接接进来了");
try {
// 读取客户端发来的数据
InputStream inputStream = socket.getInputStream();
// 将文件上传到模拟的服务器->本地磁盘
File outputfile = new File("E:\\image");//上传路径
if (!outputfile.exists()) {
outputfile.mkdirs();
}
// 路径,文件名
File file = new File(outputfile, ip + ".jpg");
// 如果文件已经存在则文件名加一
while (file.exists()) {
file = new File(outputfile, ip + "(" + (++count) + ").jpg");
}
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
fos.write(buf, 0, len);
if (file.length() > SIZE) {
System.out.println(ip + "文件体积过大");
fos.close();
socket.close();
System.out.println(ip + "....." + file.delete());
return;
}
}
// 获取socket输出流,将上传成功字样发给服务端
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传成功".getBytes());
fos.close();
socket.close();
} catch (IOException e) {
}
}
}