💥 该系列属于【Java基础编程500题】专栏,如您需查看Java基础的其他相关题目,请您点击左边的连接
目录
1. 编写一个服务器程序,接收客户端发送的消息,并将消息原样返回给客户端。
2. 实现一个文件传输服务器,客户端发送文件路径,服务器读取文件内容并发送给客户端。
3. 实现一个简单的HTTP服务器,客户端发送HTTP的GET请求,服务器返回简单的HTML页面。
4. 实现一个简单的计算器服务器,客户端发送两个数字和一个运算符(+、-、*、/),服务器返回运算结果。
5. 实现一个简单的HTTP服务器,客户端发送HTTP的POST请求,服务器返回简单的HTML页面。
✨✨ 返回题目目录 ✨ ✨
项目结构
1. 编写一个服务器程序,接收客户端发送的消息,并将消息原样返回给客户端。
(1)服务器
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) { // 创建服务器Socket
System.out.println("服务器启动,等待连接...");
Socket clientSocket = serverSocket.accept(); // 等待客户端连接
System.out.println("客户端已连接");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // 获取输入流
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // 获取输出流
String inputLine;
while ((inputLine = in.readLine()) != null) { // 读取客户端消息
System.out.println("接收到客户端消息:" + inputLine);
out.println(inputLine); // 回显消息给客户端
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
(2)客户端
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try (Socket echoSocket = new Socket("localhost", 12345); // 创建Socket连接到服务器
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true); // 获取输出流
BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); // 获取输入流
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) { // 获取键盘输入流
System.out.println("成功连接到服务器...");
String userInput;
while ((userInput = stdIn.readLine()) != null) { // 读取用户输入
out.println(userInput); // 发送消息到服务器
System.out.println("服务器回声:" + in.readLine()); // 打印服务器回声
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 实现一个文件传输服务器,客户端发送文件路径,服务器读取文件内容并发送给客户端。
(1)服务器
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
// 创建服务器端的Socket
ServerSocket serverSocket = new ServerSocket(7777);
System.out.println("文件传输服务器已启动,等待连接...");
// 等待客户端的连接
Socket socket = serverSocket.accept();
System.out.println("客户端已连接");
// 获取输入流,读取客户端发送的文件路径
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String filePath = reader.readLine();
System.out.println("客户端请求文件:" + filePath);
// 读取文件内容并发送给客户端
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] buffer = new byte[4096];
OutputStream outputStream = socket.getOutputStream();
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭资源
fileInputStream.close();
outputStream.close();
reader.close();
socket.close();
serverSocket.close();
}
}
(2)客户端
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
// 创建Socket连接到服务器
Socket socket = new Socket("localhost", 7777);
System.out.println("已连接到文件传输服务器");
// 获取键盘输入流
BufferedReader keyboardReader = new BufferedReader(new InputStreamReader(System.in));
// 获取输出流,发送文件路径到服务器
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
System.out.println("请输入文件路径:"); // 例如 copy_example.txt
String filePath = keyboardReader.readLine();
writer.println(filePath);
// 获取输入流,接收服务器发送的文件内容
InputStream inputStream = socket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("received_" + filePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
// 关闭资源
fileOutputStream.close();
inputStream.close();
writer.close();
keyboardReader.close();
socket.close();
}
}
3. 实现一个简单的HTTP服务器,客户端发送HTTP的GET请求,服务器返回简单的HTML页面。
(1)服务器
import java.io.*;
import java.net.*;
class HttpRequestHandler implements Runnable {
private final Socket socket;
public HttpRequestHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
// 获取输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 获取输出流
OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
// 读取HTTP请求行
String requestLine = reader.readLine();
// 简单的请求处理,只处理GET方法
if (requestLine.startsWith("GET")) {
// 发送HTTP响应
writer.write("HTTP/1.1 200 OK\r\n");
writer.write("Content-Type: text/html\r\n");
writer.write("\r\n");
writer.write("<html><body><h1>欢迎访问我的HTTP服务器</h1></body></html>\r\n");
writer.flush();
}
// 关闭资源
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Server {
public static void main(String[] args) throws IOException {
// 创建服务器端的Socket
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("HTTP服务器已启动,等待连接...");
while (true) {
// 等待客户端的连接
Socket socket = serverSocket.accept();
System.out.println("客户端已连接");
// 处理客户端请求
new Thread(new HttpRequestHandler(socket)).start();
}
}
}
(2)客户端
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://localhost:8080/");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("响应码:" + responseCode);
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 关闭资源
reader.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. 实现一个简单的计算器服务器,客户端发送两个数字和一个运算符(+、-、*、/),服务器返回运算结果。
(1)服务器
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8002)) {
System.out.println("计算器服务器启动,等待连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接");
// 获取输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 获取输出流
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = reader.readLine()) != null) {
String[] parts = inputLine.split(" ");
double num1 = Double.parseDouble(parts[0]);
double num2 = Double.parseDouble(parts[2]);
double result = 0;
switch (parts[1]) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) result = num1 / num2;
else result = Double.NaN;
break;
}
writer.println("结果:" + result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
(2)客户端
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8002);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
System.out.println("已连接到计算器服务器");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("请输入算术表达式(例如:5 + 3):");
String expression = scanner.nextLine();
writer.println(expression); // 发送表达式到服务器
System.out.println(reader.readLine()); // 打印服务器返回的结果
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
5. 实现一个简单的HTTP服务器,客户端发送HTTP的POST请求,服务器返回简单的HTML页面。
(1)服务器
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
// 创建服务器Socket
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("服务器启动,等待连接...");
// 等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("客户端已连接");
// 获取输入流
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// 获取输出流
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// 读取客户端发送的数据
String line;
StringBuilder data = new StringBuilder();
while ((line = in.readLine()) != null && !line.isEmpty()) {
data.append(line).append("\n");
}
// 发送响应
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/plain; charset=UTF-8");
out.println("Content-Length: " + data.length());
out.println();
out.println(data.toString());
// 关闭资源
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}
(2)客户端
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
// 创建Socket连接到服务器
Socket socket = new Socket("localhost", 8080);
System.out.println("连接到服务器");
// 获取输出流,发送POST请求
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("POST / HTTP/1.1");
out.println("Host: localhost:8080");
out.println("Content-Type: text/plain; charset=UTF-8");
out.println("Content-Length: 11");
out.println();
out.println("Hello World");
// 获取输入流,读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
// 关闭资源
in.close();
out.close();
socket.close();
}
}