📅  最后修改于: 2023-12-03 15:10:16.241000             🧑  作者: Mango
这是一道来自 UGC NET CS 2018 年 12 月 – II 考试的编程问题,通过这道题目,可以考察程序员的编程能力和对计算机网络的了解以及熟练程度。
假设有以下几个条件:
请用 Python 3.x 编写一个程序满足以上条件,并按照以下要求实现:
服务端代码如下:
import socket
import threading
class Server:
def __init__(self):
self.server_host = '127.0.0.1'
self.server_port = 8888
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def start(self):
self.server_socket.bind((self.server_host, self.server_port))
self.server_socket.listen(5)
print('Server is listening on {}:{}'.format(self.server_host, self.server_port))
while True:
client_socket, client_address = self.server_socket.accept()
print('Accepted connection from {}:{}'.format(client_address[0], client_address[1]))
client_handler = threading.Thread(target=self.handle_client, args=(client_socket,))
client_handler.start()
def handle_client(self, client_socket):
try:
while True:
data = client_socket.recv(1024)
if not data:
break
client_message = data.decode('utf-8')
print('Received message from client: {}'.format(client_message))
server_message = 'Hello Client'
client_socket.sendall(server_message.encode('utf-8'))
except Exception as e:
print('Error occurred while handling client: {}'.format(e))
finally:
print('Closing client socket..')
client_socket.close()
if __name__ == '__main__':
server = Server()
server.start()
客户端代码如下:
import socket
class Client:
def __init__(self):
self.server_host = '127.0.0.1'
self.server_port = 8888
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, message):
self.client_socket.connect((self.server_host, self.server_port))
print('Connected to server at {}:{}'.format(self.server_host, self.server_port))
self.client_socket.sendall(message.encode('utf-8'))
data = self.client_socket.recv(1024)
server_message = data.decode('utf-8')
print('Received message from server: {}'.format(server_message))
if __name__ == '__main__':
client = Client()
client.connect('Hello Server')
以上代码实现了一个简单的 TCP 通信,其中服务端可以通过多线程实现并发处理多个客户端的连接请求。客户端和服务端的代码独立编写成类,可以实现重用和代码封装。