写一段代码实现使用原始socket()实现一个C/S架构的应用,支持服务器时间回显示; 要求:从客户端发送命令,接收服务器的时间并显示到终端;
时间: 2023-06-03 11:05:57 浏览: 83
好的,以下是实现C/S架构的应用,支持服务器时间回显的代码:
服务器端代码:
```
import socket
import time
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 9999))
server_socket.listen(1)
while True:
client_socket, client_address = server_socket.accept()
print(f"Connection from client {client_address}")
data = client_socket.recv(1024)
if data.decode() == 'get_time':
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
client_socket.send(current_time.encode())
client_socket.close()
```
客户端代码:
```
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 9999))
command = 'get_time'
client_socket.send(command.encode())
response = client_socket.recv(1024)
print(f"Server time: {response.decode()}")
client_socket.close()
```
客户端发送命令'get_time'到服务器端,服务器端接收到命令后,获取当前时间,并通过socket发送给客户端,客户端再将服务器时间回显到终端。