需求:编写客户端和服务器端程序,客户端用于上传图片,服务器端用于接收文件,文件上传成功后,给客户端一个反馈:文件上传成功。
注意:
服务器端采用多线程实现,并且要解决文件名冲突问题。
上传的路径必须是一个文件,且文件类型必须是jpg,两个条件但凡有一个不满足,都需要重新录入,直到正确为止,具体效果如下图:
客户端控制台内容:
我的D盘目录:
客户类
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class UploadClient {
public static void main(String[] args) {
Socket s = null;
BufferedInputStream bis = null;
try {
//创建客户端Socket对象
s = new Socket("192.168.43.134", 10000);
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入上传文件的路径:");
String filePath = sc.nextLine();
File file = new File(filePath);
if (!file.isFile() || !file.getName().endsWith(".jpg")) {
System.out.println("请输入正确的图片文件路径,请重新输入");
} else {
//封装文件的数据
bis = new BufferedInputStream(new FileInputStream(file));
//封装输出流写数据
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
byte[] bys = new byte[1024];
int len;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
bos.flush();
}
s.shutdownOutput();
//接收反馈
BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
String data = brClient.readLine(); //等待读取数据
System.out.println("服务器的反馈:" + data);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服务器类
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class UploadServer {
public static void main(String[] args) throws IOException {
//创建服务器Socket对象
ServerSocket ss = new ServerSocket(10000);
while (true) {
//监听客户端连接,返回一个对应的Socket对象
Socket s = ss.accept();
//为每一个客户端开启一个线程
new Thread(new UploadThread(s)).start();
}
}
}
线程类
import java.io.*;
import java.net.Socket;
import java.nio.Buffer;
public class UploadThread implements Runnable {
private Socket s;
public UploadThread(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
//接收数据写到文件
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
//解决名称冲突问题
int count = 0;
File file = new File("itheima_javase_exam2\\Copy[" + count + "].jpg");
while (file.exists()) {
count++;
file = new File("itheima_javase_exam2\\Copy[" + count + "].jpg");
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] bys = new byte[1024];
int len;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
bos.flush();
}
//给出反馈
BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bwServer.write("文件上传成功");
bwServer.newLine();
bwServer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(s!=null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}