使用多线程技术实现只要有一个客户上传文件,就开启一个线程,完成文件的上传。
TCP通信的客户端代码:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
//模拟C/S服务器上传文件
//文件上传到客户端
public class TCPClient {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("d:\\1.png");
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream os = socket.getOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1){
os.write(bytes, 0, len);
}
socket.shutdownOutput(); //上传完文件,给服务器写一个结束标记,不然会发生阻塞状态
InputStream is = socket.getInputStream();
while ((len = is.read(bytes)) != -1){
System.out.println(new String(bytes, 0, len));
}
fis.close();
os.close();
}
}
TCP通信的服务器端代码:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
//文件上传到服务器端
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
//让服务器一直处于监听状态(死循环)
while (true) {
Socket socket = server.accept();
//使用多线程技术,有一个客户上传文件,就开启一个线程,完成文件上传
new Thread(new Runnable() {
//完成文件上传
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
File file = new File("d:\\upload");
if (!file.exists()){
file.mkdirs();
}
//自定义文件命名规则:域名 + 毫秒值 + 随机数
String filename = "hucm" + System.currentTimeMillis() + new Random().nextInt(999999) + ".jpg";
FileOutputStream fos = new FileOutputStream(file + "\\" + filename); // 注意此处的路径书写
int len = 0;
byte[] bytes = new byte[1024];
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
socket.getOutputStream().write("文件上传成功".getBytes());
fos.close();
socket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}).start();
}
//server.close();服务器就没必要关闭
}
}