服务器端
package wangl.net.upload;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
/**
* @package: wangl.net.upload
* @author: wanglei
* @date: 2021/12/14 10:25
*/
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8000);
//使用死循环,让服务器一直处于运行
while (true){
Socket socket = serverSocket.accept();//获取请求的客户端Socket
InputStream inputStream = socket.getInputStream();
//文件夹是否存在,不存在就新建
File file = new File("C:\\Mystic\\pwx");//copy请更换路径
if (!file.exists()){
file.mkdirs();
}
//自定义文件命名规则,毫秒值连接随机数
String filename = (long)System.currentTimeMillis()+new Random(100).nextInt()+".jpg";
FileOutputStream fos = new FileOutputStream(file+"\\"+filename);
int len = 0;
byte[] bytes = new byte[1024];
while ((len=inputStream.read(bytes))!=-1){
fos.write(bytes, 0, len);
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传成功".getBytes());
fos.close();
socket.close();
}
}
}
客户端
package wangl.net.upload;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 文件上传客户端
* @package: wangl.net.upload
* @author: wanglei
* @date: 2021/12/14 9:58
*/
public class TCPClient {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("C:\\Mystic\\wanglei\\04.jpg");
Socket socket = new Socket("127.0.0.1",8000);
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 inputStream = socket.getInputStream();
int i = inputStream.read(bytes);
System.out.println(new String(bytes,0,i));
socket.close();
fis.close();
}
}
先运行服务器端,再运行客户端
查看服务器端写的路径里,已经有了上传的文件