python socket聊天室(tcp serverclient)
Posted 王者小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python socket聊天室(tcp serverclient)相关的知识,希望对你有一定的参考价值。
import socket,os,hmac,pickle,threading,datetime class Server: def __init__(self,secret_key): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.addr = (\'127.0.0.1\', 8088) self.users = {} self.secret_key = secret_key def start_server(self): try: self.sock.bind(self.addr) except Exception as e: print(e) self.sock.listen(5) print("服务器已开启,ip地址为{}等待连接...".format(self.addr)) self.accept_cont() def __auth(self,sock,addr,secret_key): print(\'来自{}的客户端发起连接,开始验证客户端合法性...\'.format(addr)) msg = os.urandom(32) sock.sendall(msg) h = hmac.new(secret_key, msg, digestmod=\'md5\') digest = h.digest() response = sock.recv(len(digest)) return hmac.compare_digest(digest, response) def accept_cont(self): while True: sock,addr = self.sock.accept() if not self.__auth(sock,addr,self.secret_key): print(\'来自{}的客户端验证失败,关闭连接!\'.format(addr)) sock.close() else: print(\'来自{}的客户端验证通过!\'.format(addr)) self.users[addr] = sock number = len(self.users) print("用户{}连接成功!现在共有{}位用户".format(addr, number)) threading.Thread(target=self.recv_send, args=(sock, addr)).start() def recv_send(self,sock,addr): while True: try: response = pickle.loads(sock.recv(4096)) msg = "{}用户{}发来消息:{}".format(self.get_time(), addr, response) for client in self.users.values(): client.send(pickle.dumps(msg)) except ConnectionResetError: print("用户{}已经退出!".format(addr)) self.users[addr].close() self.users.pop(addr) msg = "{}用户{}已经退出!".format(self.get_time(), addr) for client in self.users.values(): client.send(pickle.dumps(msg)) break def close_server(self): for client in self.users.values(): client.close() self.sock.close() os._exit(0) def get_time(self): now = datetime.datetime.now() send_time = now.strftime("%Y-%m-%d %H:%M:%S") return send_time def run(self): threading.Thread(target=self.start_server).start() while True: cmd = input("input \'exit\' to stop sever! >>>") if cmd == "exit": self.close_server() else: print("输入命令无效,请重新输入!") secret_key = b\'I have a red phone!\' server = Server(secret_key) server.run()
客户端:
import socket,hmac,pickle,threading,os class Client: """""" def __init__(self,ip_port,secret_key): self.ip_port = ip_port self.secret_key = secret_key self.client = self.conn_server() self.active = True def conn_server(self): client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.setsockopt(socket.SOL_SOCKET,socket.SO_KEEPALIVE,True) err = client.connect_ex(self.ip_port) if err != 0: print("please check sever\'s ip_port!") return None msg = client.recv(32) h = hmac.new(self.secret_key, msg, digestmod=\'md5\') digest = h.digest() client.sendall(digest) return client def send_msg(self): def send_msg2(client): msg = input(\'input you words:>>>\').strip() if msg in [\'quit\',\'exit\']: print(\'you just closed the connection.\') client.close() self.active = False else: client.sendall(pickle.dumps(msg)) while self.active: send_msg2(self.client) def recv_msg(self): while True: try: data = self.client.recv(1024) except Exception as err: print(\'you just lost the connection.err:\',err) self.client.close() break print(\'recv msg:\',pickle.loads(data)) os._exit(0) def run(self): threading.Thread(target=self.recv_msg).start() self.send_msg() ip_port = (\'127.0.0.1\',8088) secret_key = b\'I have a red phone!\' client0 = Client(ip_port,secret_key) client0.run()
以上是关于python socket聊天室(tcp serverclient)的主要内容,如果未能解决你的问题,请参考以下文章
游戏开发实战Unity使用Socket通信实现简单的多人聊天室(万字详解 | 网络 | TCP | 通信 | Mirror | Networking)
游戏开发实战Unity使用Socket通信实现简单的多人聊天室(万字详解 | 网络 | TCP | 通信 | Mirror | Networking)