客户端代码
"""
客户端:
1、输入用户名
2、发送用户名
3、等待进入聊天室 Y进入聊天室 N重新回到第一步
传输通信协议设计:数据传输中双方做一些数据格式和含义的约定
请求类型 数据参量
进入聊天室 L name
聊天 C 消息内容
退出 E exit
"""
from socket import *
from multiprocessing import Process
import sys
HOST = "127.0.0.1"
POST = 8000
ADDR = (HOST, POST)
def login(sock):
name = input("name:")
msg = "L " + name
sock.sendto(msg.encode(), ADDR)
result, addr = sock.recvfrom(128)
if result.decode() == "OK":
print("您已经进入聊天室")
return name
else:
print("姓名重复,请更换")
def recv_msg(sock):
while True:
data, addr = sock.recvfrom(2048)
print("\n" + data.decode() + "\n我:", end=" ")
def send_msg(sock, name):
while True:
try:
msg = input("我:")
except KeyboardInterrupt:
msg = "exit"
if msg == 'exit':
data = "E " + name
sock.sendto(data.encode(), ADDR)
sys.exit("您已退出聊天室")
data = "C %s %s" % (name, msg)
sock.sendto(data.encode(), ADDR)
def main():
sock = socket(AF_INET, SOCK_DGRAM)
name = login(sock)
p = Process(target=recv_msg, args=(sock,))
p.daemon = True
p.start()
send_msg(sock, name)
p.join()
if __name__ == '__main__':
main()
服务端代码
"""
author: Levi
email: lvze@tedu.cn
time: 2020-7-14
env: Python3.6
socket and Process exercise
"""
from socket import *
from multiprocessing import Process
HOST = "0.0.0.0"
PORT = 8000
ADDR = (HOST, PORT)
user = {}
def do_login(sock, name, address):
if name in user or "管理" in name:
sock.sendto(b"FAIL", address)
return
else:
sock.sendto(b"OK", address)
msg = "欢迎 %s 进入聊天室" % name
for i in user:
sock.sendto(msg.encode(), user[i])
user[name] = address
def do_chat(sock, name, content):
msg = "%s : %s" % (name, content)
for i in user:
if i != name:
sock.sendto(msg.encode(), user[i])
def do_exit(sock, name):
del user[name]
msg = "%s 退出聊天室" % name
for i in user:
sock.sendto(msg.encode(), user[i])
def handle(sock):
while True:
data, addr = sock.recvfrom(1024)
tmp = data.decode().split(' ', 2)
if tmp[0] == 'L':
do_login(sock, tmp[1], addr)
elif tmp[0] == 'C':
do_chat(sock, tmp[1], tmp[2])
elif tmp[0] == 'E':
do_exit(sock, tmp[1])
def main():
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(ADDR)
p = Process(target=handle, args=(sock,))
p.daemon = True
p.start()
while True:
content = input("管理员消息:")
if content == "quit":
break
data = "C 管理员消息 " + content
sock.sendto(data.encode(), ADDR)
if __name__ == '__main__':
main()
|