一、服务端
import socket
import random
import threading
def creat_chatroom():
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',9999))
s.listen(5)
print('聊天室已经创建')
return s
#给其他用户发送消息
def send_message(data):
for conn in client:
conn.send(data)
#生成随机昵称
def random_name():
name=random.choice(['香蕉','苹果','梨','橘子','桃子','西瓜','草莓','菠萝'])
for i in range(3):
name+=random.choice('123456789')
return name
def fun(conn,addr):
name=random_name()
users[addr]=conn
client[conn]=name
send_message(bytes(f'欢迎{name}加入聊天室',encoding='utf-8'))
while True:
try:
data=conn.recv(1024)
data=f'{client[conn]}说:{data.decode("utf-8")}'
send_message(bytes(data,encoding='utf-8'))
except:
print(f'{users[addr]}已经断开连接')
data=bytes(f'{users[addr]}已经断开连接',encoding='utf-8')
del users[addr]
del client[conn]
send_message(data)
break
def main():
s=creat_chatroom()
global users,client
users={}
client={}
while True:
conn,addr=s.accept()
threading.Thread(target=fun,args=(conn,addr)).start()
s.close()
if __name__ == '__main__':
main()
二、客户端
import socket
import threading
def creat_thread(s):
while True:
data=input('请输入消息:')
if data!='exit':
s.send(bytes(data,encoding='utf-8'))
else:
s.close()
break
def main():
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# creat_thread(s)
s.connect(('127.0.0.1',9999))
threading.Thread(target=creat_thread,args=(s,)).start()
while True:
try:
data=s.recv(1024)
print(data.decode('utf-8')+'\n')
except:
print('已经断开连接\n')
break
s.close()
if __name__ == '__main__':
main()
|