import socket import sys import _thread as t dictd={} listd=[] def boradcast(fileno,message): for conn in listd: if conn.fileno()!=fileno: conn.sendall(message.encode()) def cilentThred(conn,fileno): conn.sendall("欢迎:{0}".format(fileno).encode()) data = conn.recv(1024).decode() dictd[fileno] = data listd.append(conn) print("昵称为:{0}".format(dictd[fileno])) boradcast(fileno,"[系统提示:<{0}>进入聊天室]".format(dictd[fileno])) while True: try: datadd = conn.recv(1024).decode() if datadd: print("【消息】{0}:{1}".format(dictd[fileno], datadd)) boradcast(fileno, "{0}:{1}".format(dictd[fileno],datadd)) except : try: listd.remove(conn) except: pass print("[日志]{0}退出聊天室,当前聊天室人数为{1}人".format(dictd[fileno],len(listd))) boradcast(fileno, "【系统提示】:{0}离开聊天室".format(dictd[fileno])) conn.close() return pass try: sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print('服务器socket创建成功') except: print('创建失败') sys.exit(0) address=('172.3.14.125',8898) sockets.bind(address) sockets.listen(5) while True: conn, addr = sockets.accept() print('客户端{0}连接成功'.format(conn.fileno())) t.start_new_thread(cilentThred,(conn,conn.fileno())) conn.close()
import socket import threading import sys try: sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print('客户端socket创建成功') except: print('创建失败') sys.exit(0) address=('172.3.14.125',8898) sockets.connect(address) data = sockets.recv(1024).decode() print(data) nic=input("输入昵称:") sockets.sendall(nic.encode()) def send(): while True: try: myword=input("请输入:") sockets.sendall(myword.encode()) except: pass def reced(): while True: try: otherword=sockets.recv(1024).decode() if otherword: print(otherword) except: pass t1=threading.Thread(target=send) t2=threading.Thread(target=reced) t2.start() t1.start() #t1.join() #sockets.close()