服务端
from socket import *
import os
ADDR = ("127.0.0.1", 8888)
user = {}
def login(s, name, addr):
if name in user or "管理" in name:
s.sendto(b"FAIL", addr)
return
else:
s.sendto(b"OK", addr)
msg = "\n欢迎 %s 进入聊天室" % name
for i in user:
s.sendto(msg.encode(), user[i])
user[name] = addr
def transfer(s, name, msg_content):
msg = "\n%s:%s" % (name, msg_content)
for i in user:
if i != name:
s.sendto(msg.encode(), user[i])
def quit(s, name):
msg = "\n%s 退出聊天室" % name
for i in user:
if i != name:
s.sendto(msg.encode(), user[i])
else:
s.sendto(b"EXIT", user[i])
del user[name]
def manager_message(s):
while True:
content = input(">>>")
msg = "CHAT 管理员消息 %s" % content
s.sendto(msg.encode(), ADDR)
def main():
s = socket(AF_INET, SOCK_DGRAM)
s.bind(ADDR)
pid = os.fork()
if pid < 0:
print("Error")
elif pid == 0:
manager_message(s)
else:
while True:
data, addr = s.recvfrom(1024)
tmp = data.decode().split(" ", 2)
if tmp[0] == "CONNECT":
login(s, tmp[1], addr)
elif tmp[0] == "CHAT":
transfer(s, tmp[1], tmp[2])
elif tmp[0] == "QUIT":
quit(s, tmp[1])
if __name__ == "__main__":
main()
客户端
from socket import *
import os, sys
ADDR = ("127.0.0.1", 8888)
def main():
s = socket(AF_INET, SOCK_DGRAM)
while True:
name = input("请输入姓名:")
msg = "CONNECT %s" % name
s.sendto(msg.encode(), ADDR)
feedback, addr = s.recvfrom(1024)
if feedback == b"OK":
print("您已进入聊天室")
break
else:
print("该用户已存在")
pid = os.fork()
if pid < 0:
print("Error!")
return
elif pid == 0:
while True:
try:
content = input(">>>")
except:
content = "quit"
if content == "quit":
msg = "QUIT %s" % name
s.sendto(msg.encode(), ADDR)
sys.exit("您已退出群聊")
else:
msg_send = "CHAT %s %s" % (name, content)
s.sendto(msg_send.encode(), ADDR)
else:
while True:
data, addr = s.recvfrom(1024)
if data == b"EXIT":
sys.exit()
print(data.decode() + "\n>>>", end="")
if __name__ == "__main__":
main()