1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| import socket,threading,time
clients = {}
class client(object): def __init__(self,socket,addr,username): self.addr = addr[0] self.port = addr[1] self.username = username self.socket=socket
def sendMsg(self,msg,username,admin): try: if admin: self.socket.send(("%s %s(管理员): %s" % (self.getTime(), username, msg)).encode("utf-8")) else: self.socket.send(("%s %s: %s" %(self.getTime(), username, msg)).encode("utf-8")) return True except: return False
def recv(self,mtu=1024): try: data = self.socket.recv(mtu).decode("utf-8") if data == "-!-quit-!-" or not data: return False return data except: return False
def close(self): try: self.socket.close() return True except: return False
def getId(self): return "%s-%s" % (self.addr,self.port) def getTime(self): return str(time.strftime("%Y-%m-%d %H:%M:%S"))
def new_client(c): try: print("%s(%s) 尝试连接" %(c.addr,c.port)) data = c.recv() if not data: return if len(data) >= 16: c.socket.send("用户名太长了") return c.username = data print("用户%s %s(%s)已连接" %(c.username,c.addr,c.port)) c.socket.send("已连接".encode("utf-8")) while True: data = c.recv() if not data: break else: print("用户%s %s(%s) 发送了: %s" % (c.username,c.addr, c.port, data)) broadcast(data,c.username)
except socket.errno as e: print("Socket error: %s" % str(e)) except Exception as e: print("Other exception: %s" % str(e)) finally: print("%s(%s) 断开连接" % (c.addr, c.port)) c.close() clients.pop(c.getId())
def broadcast(msg,username,admin=False): for c in clients.values(): c.sendMsg(msg,username,admin)
def start_server(port): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = "192.168.153.1" server.bind((host, port))
server.listen(10) print("服务器已开启,正在监听{}".format(server.getsockname()))
while True: conn, addr = server.accept() c = client(conn,addr,"") clients[c.getId()] = c t = threading.Thread(target=new_client, args=(c,)) t.start()
if __name__ == "__main__": start_server(23333) print("服务器已关闭")
|