编写程序,客户端发送一个文件名给服务器,服务器查找本地磁盘,如果文件存在,则把文件内容发送个客户端,否则回答文件不存在
立即下载
资源介绍:
编写程序,客户端发送一个文件名给服务器,服务器查找本地磁盘,如果文件存在,则把文件内容发送个客户端,否则回答文件不存在。
import java.io.*;
import java.net.*;
public class SimplifiedServer {
private static final int PORT = 12345;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("服务器在在接收指令" + PORT);
while (true) {
Socket socket = serverSocket.accept();
handleClient(socket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClient(Socket socket) {
new Thread(() -> {
try (
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
) {
String fileName = in.readLine();
File file = new File(fileName);
if (file.exists()) {
try (BufferedReader fileReader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = fileReader.readLine()) != null) {
out.println(line);
}
}
} else {
out.println("文件未找到");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// Ignore
}
}
}).start();
}
}