帮我用java写一个简易的基于C/S的图书管理系统
时间: 2023-06-18 09:02:30 浏览: 96
java基于c/s的图书管理系统
4星 · 用户满意度95%
好的,下面是一个简单的基于C/S的图书管理系统的Java代码:
服务端(Server.java):
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,IP地址为:" + socket.getInetAddress().getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while (true) {
String request = reader.readLine();
System.out.println("接收到客户端请求:" + request);
if ("exit".equals(request)) {
System.out.println("客户端已断开连接");
break;
}
String response = handleRequest(request);
writer.write(response + "\n");
writer.flush();
System.out.println("发送响应给客户端:" + response);
}
reader.close();
writer.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String handleRequest(String request) {
// 处理请求的逻辑
return "请求已处理";
}
}
```
客户端(Client.java):
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 8888);
System.out.println("已连接到服务器");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("请输入命令:");
String command = consoleReader.readLine();
writer.write(command + "\n");
writer.flush();
String response = reader.readLine();
System.out.println("服务器响应:" + response);
if ("exit".equals(command)) {
break;
}
}
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码只是一个简单的示例,实现的功能也很简单,只是简单地通过控制台输入命令,并将命令发送给服务端,服务端收到命令后做出相应的处理,并将处理结果返回给客户端。在实际开发中,需要根据需求来设计更加完善的功能。
阅读全文