效果:
服务端代码:
import socket, threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 8080))
server.listen(1000)
def broadCastMSG(users, msgNo, msg, selfLink): #向所有用户广播消息, 除了自己
for user,link in users:
if link != selfLink:
link.send((msgNo).to_bytes(4, byteorder = "big"))
link.send(len(msg).to_bytes(4, byteorder = "big"))
link.send(msg)
def res(link, addr, users, nickName):
while True:
msg, data = getAMSG(link)
if msg == 1:
nickNamet = nickName + " :"
broadCastMSG(users, 1, nickNamet.encode("utf-8") + data, link)
def getAMSG(link): #得到一条消息
msg = int.from_bytes(link.recv(4), byteorder = "big") #消息类型
length = int.from_bytes(link.recv(4), byteorder = "big") #消息长度
data = []
while length > 0:
if length > 1024:
data.append(link.recv(1024))
else:
data.append(link.recv(length))
length = length - 1024
data_bytes = b"".join(data)
return (msg, data_bytes)
users = [] #用户列表
while True:
link, addr = server.accept()
msg, data_bytes = getAMSG(link)
nickName = data_bytes.decode("utf-8")
print(nickName, "加入聊天室:")
users.append((nickName, link))
broadCastMSG(users, 0, data_bytes, link)
threading.Thread(target = res, args = (link,addr, users, nickName)).start()
"""
向客户端发送的消息:
0 : 表示有连接进入,后跟昵称
1 : 表示有新的消息,后跟消息
2 : 表现有用户退出,后跟昵称(没有实现)
"""
客户端代码:
import socket, threading
link = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
link.connect(("localhost", 8080))
nickName = ""
while (nickName == "" or (" " in nickName)):
nickName = input("请输入昵称:")
link.send((0).to_bytes(4, byteorder="big"))
link.send((len(nickName)).to_bytes(4, byteorder="big"))
link.send(nickName.encode("utf-8"))
def getAMSG(link): #得到一条消息
msg = int.from_bytes(link.recv(4), byteorder = "big") #消息类型
length = int.from_bytes(link.recv(4), byteorder = "big") #消息长度
data = []
while length > 0:
if length > 1024:
data.append(link.recv(1024))
else:
data.append(link.recv(length))
length = length - 1024
data_bytes = b"".join(data)
return (msg, data_bytes)
def getMSG(link): #不停接收来自服务器的消息
while (True):
msg, data = getAMSG(link)
if msg == 0:
print(data.decode("utf-8"), "进入聊天室")
elif msg == 1:
print(data.decode("utf-8"))
def sendAMSG(link, msgNo, msg): #发送一条消息
link.send((msgNo).to_bytes(4, byteorder="big"))
link.send(len(msg).to_bytes(4, byteorder="big"))
link.send(msg)
threading.Thread(target = getMSG, args = (link,)).start()
while(True):
msg = input()
if msg != "":
sendAMSG(link, 1, msg.encode("utf-8"))
"""
客户端向服务端发的消息:
0:表示初次连接,提供用户名
1:表示发送给公众聊天室的消息
"""