用Java2.请使用Socket类、ServerSocket类等编写一个套接字程序。服务器端提供报时服务:当客户端发送出“几点了?”,服务器端向客户端返回“15:40”;若客户端发送“今天是几号?”,服务器端向客户端返回“5月22日”;若客户端发送“今天是星期几?”,服务器端向客户端返回“星期一”;客户端收到数据后将在命令行窗口中显示收到的时间信息;当客户端发送“再见”时,则服务器端结束对该客户端的服务;服务器端可以同时与多个客户端建立连接,并为它们提供报时服务。 提示:请采用恰当的流类型实现数据的收发;服务器端若同时服务多个客户端应采用多线程技术;结束对某个客户的服务可以通过关闭socket对象实现。 可先完成服务器端为单一客户端提供服务的代表编写,完成后再加入多线程以完善代码。
时间: 2023-09-22 09:05:41 浏览: 66
以下是一个简单的实现:
服务器端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started at " + new Date());
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Connection from " + socket.getRemoteSocketAddress());
new Thread(() -> {
try {
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
String request = new String(buffer, 0, length);
String response;
switch (request.trim()) {
case "几点了?":
response = new Date().toString();
break;
case "今天是几号?":
response = String.format("%tm月%td日", new Date(), new Date());
break;
case "今天是星期几?":
response = String.format("%tA", new Date());
break;
case "再见":
response = "Goodbye!";
break;
default:
response = "I don't understand.";
}
outputStream.write(response.getBytes());
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Please input your request: ");
String request = scanner.nextLine();
outputStream.write(request.getBytes());
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
String response = new String(buffer, 0, length);
System.out.println("Response: " + response);
if (request.trim().equals("再见")) {
break;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
运行服务器端代码后,可以同时运行多个客户端进行测试。
阅读全文