下面是一个简单的Python Socket编程示例,实现了一个基本的即时通讯功能。这个例子包括一个服务器端和一个客户端。
服务器端(Server):
python import socket import threading class Server: def __init__(self, host = '127.0.0.1', port = 55555): self.host = host self.port = port self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind((self.host, self.port)) self.server.listen() self.clients = [] self.nicknames = [] def broadcast(self, message): for client in self.clients: client.send(message) def handle(self, client): while True: try: message = client.recv(1024) self.broadcast(message) except: index = self.clients.index(client) self.clients.remove(client) client.close() nickname = self.nicknames[index] self.nicknames.remove(nickname) self.broadcast(f'{nickname} left the chat!'.encode('ascii')) break def receive(self): while True: client, address = self.server.accept() print(f'Connected with {str(address)}') client.send('NICK'.encode('ascii')) nickname = client.recv(1024).decode('ascii') self.nicknames.append(nickname) self.clients.append(client) print(f'Nickname of the client is {nickname}!') self.broadcast(f'{nickname} joined the chat!'.encode('ascii')) client.send('Connected to the server!'.encode('ascii')) thread = threading.Thread(target=self.handle, args=(client,)) thread.start()
客户端(Client):
python import socket import threading class Client: def __init__(self, host = '127.0.0.1', port = 55555): self.nickname = input("Enter nickname: ") self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.connect((host, port)) print("Connected to the server!") self.receive() def receive(self): while True: try: message = self.client.recv(1024).decode('ascii') if message == 'NICK': self.client.send(self.nickname.encode('ascii')) else: print(message) except: print("Error occurred!") break def send(self, message): self.client.send(message.encode('ascii'))