利用Socket类和ServerSocket类编写一个C/S程序,实现C/S通信。 客户端向服务器端发送请求给服务端,形式如“From 学号 姓名: what time is it ”;服务器端接受到该字符串后将服务器端当前时间返回给客户端,形式如“To 姓名: 当前时间”;客户端向服务器端发送“From 学号 姓名:Exit”命令,服务器端向客户端返回“To 姓名:Bye”后退出。
时间: 2024-03-22 13:42:16 浏览: 92
好的,这是一个基于 Socket 的简单 C/S 通信的例子。下面是 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("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,地址:" + socket.getInetAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
String line;
while ((line = reader.readLine()) != null) {
if (line.equals("exit")) {
System.out.println("客户端已断开连接");
writer.println("Bye");
socket.close();
break;
}
String[] request = line.split(":");
String name = request[0].substring(5);
String message = request[1].trim();
if (message.equals("what time is it")) {
String time = new java.util.Date().toString();
writer.println("To " + name + ": " + time);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入您的学号和姓名:");
String info = console.readLine();
while (true) {
System.out.print("请输入您要发送的消息:");
String message = console.readLine();
writer.println("From " + info + ": " + message);
String response = reader.readLine();
System.out.println(response);
if (response.equals("Bye")) {
socket.close();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个例子中,服务端监听 8888 端口,客户端连接服务端后可以发送消息给服务端,服务端接收到消息后解析出发送者的姓名和消息内容,如果消息内容是 "what time is it",则返回当前时间给客户端,如果消息内容是 "Exit",则服务端向客户端返回 "Bye" 并关闭连接。
阅读全文