服务端代码:
package io.upload;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class UploadServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8888);
while (true){
// 使用多线程,重写Runnable接口
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
File file = new File("E:\\upload");
if (!file.exists()){
file.mkdirs();
}
/*
自定义文件名:
规则:域名+毫秒数+随机数
*/
String fileName = "chincan" + System.currentTimeMillis() + new Random().nextInt(99999) + ".rpm";
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);
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传成功".getBytes());
fos.close();
socket.close();
} catch (IOException e){
e.printStackTrace();
}
}
}).start();
}
}
}
客户端:
void shutdownOutput(); // 上传完成后发送给服务器一个结束标记以解决阻塞问题
demo:
package io.upload;
import java.io.*;
import java.net.Socket;
public class UploadClient {
public static void main(String[] args) throws IOException {
FileInputStream fi = new FileInputStream("E:\\elk\\elasticsearch-7.14.1-x86_64.rpm");
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream os = socket.getOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = fi.read(bytes)) != -1){
os.write(bytes, 0 ,len);
}
// void shutdownOutPut 禁用此套接字的输出流
// 上传完服务器后给服务器一个结束标记,解决阻塞问题
socket.shutdownOutput();
// 读服务器回写数据
InputStream is = socket.getInputStream();
while ((len = is.read(bytes)) != -1){
System.out.println(new String(bytes, 0, len));
}
fi.close();
socket.close();
}
}