基于TCP的在线聊天室搭建
服务器端代码
import socket
import threading
import json
class User:
def __init__(self, uid: int, username: str, addr: tuple):
self.username = username
self.uid = uid
self.addr = addr
class ChatRoom:
def __init__(self):
self.users = {}
self.conns = {}
self.semaphore = threading.Semaphore()
self.uid = 0
user = User(-1, "聊天室", ())
self.users[-1] = user
def addUser(self, user: User, socket: socket.socket):
self.semaphore.acquire()
self.conns[user.uid] = socket
self.users[user.uid] = user
thread = threading.Thread(target=self.reveive_single_user_msg, args=(user, socket))
thread.start()
self.semaphore.release()
def removeUser(self, user: User):
self.semaphore.acquire()
self.conns.pop(user.uid)
self.users.pop(user.uid)
self.semaphore.release()
def reveive_single_user_msg(self, user: User, socket: socket.socket):
msg = {"uid": -1, "body": user.username+"进入聊天室 ("+"在线"+ str(len(self.users.keys())-1) +"人)"}
self.send_to_all(msg)
try:
while True:
recv_data = socket.recv(1024)
if len(recv_data) == 0:
self.removeUser(user)
break
msg = json.loads(recv_data)
self.send_to_all(msg)
except:
msg['uid'] = -1
msg['body'] = "["+user.username+"]:"+ "退出聊天室 ("+"在线"+ str(len(self.users.keys())-2) +"人)"
self.send_to_all(msg)
self.removeUser(user)
def send_to_all(self, msg: dict):
self.semaphore.acquire()
message = "["+self.users[msg['uid']].username+"]: "+msg['body']
print(message)
for key in self.conns.keys():
try:
if key == msg['uid']:
continue
except:
print(msg)
continue
msg_f = {'username': self.users[msg['uid']].username, 'body': msg['body']}
msg_s = json.dumps(msg_f)
try:
self.conns[key].send(msg_s.encode("utf-8"))
except:
pass
self.semaphore.release()
class Controller:
def __init__(self, chatroom: ChatRoom):
self.chatroom = chatroom
def run(self):
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = ("", 4566)
tcp.bind(addr)
tcp.listen(100)
print("==========聊天室启动==========")
print("%s:%d" % (socket.gethostbyname(socket.gethostname()), 4566))
while True:
try:
clientSocket, clientAddr = tcp.accept()
print(clientAddr)
msg = {"uid": self.chatroom.uid, "body": "欢迎进入聊天室\n"}
self.chatroom.uid += 1
msg_s = json.dumps(msg)
clientSocket.send(msg_s.encode("utf-8"))
# 接受用户信息传送
userInfo = clientSocket.recv(1024)
userInfo = json.loads(userInfo)
user = User(userInfo['uid'], userInfo['username'], clientAddr)
self.chatroom.addUser(user, clientSocket)
except:
pass
tcp.close()
if __name__ == '__main__':
controller = Controller(ChatRoom())
controller.run()
客户端代码
import socket
import json
import threading
# 服务器 IP和端口
server_ip = ("47.240.94.178", 4566)
username = None
end = False
def connect(username):
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.connect(server_ip)
msg = tcp.recv(1024)
msg = json.loads(msg)
print(msg['body'])
uid = msg['uid']
msg = {}
msg['uid'] = uid
msg['username'] = username
msg_s = json.dumps(msg)
tcp.send(msg_s.encode("utf-8"))
thread = threading.Thread(target=receive, args=(tcp,))
thread.start()
while True:
data = input("[" + username + "]:")
data = data.split()
if (not data[0].isnumeric()) or (int(data[0])!=0 and int(data[0])!=1):
print("输入不合法!![:数字(0退出 1发送) 内容]")
continue
if (len(data) == 1) and int(data[0])==0:
break
if int(data[0]) == 0:
break
msg = {}
if int(data[0]) == 1:
msg['uid'] = uid
msg['body'] = ' '.join(data[1:])
msg_s = json.dumps(msg)
tcp.send(msg_s.encode("utf-8"))
tcp.close()
def receive(tcp: socket.socket):
while True:
try:
msg = tcp.recv(1024)
msg = json.loads(msg.decode("utf-8"))
print("")
print("["+msg['username']+"]:", msg['body'])
print("["+username+"]:", end=" ", flush=True)
except:
break
if __name__ == '__main__':
username = input("用户名:")
username = username.strip()
connect(username)
CharRoom.py是服务器端代码
User.py是客户端代码
自己搭建一个在线聊天室
将ChatRoom.py上传到服务器
直接python3 ChatRomm.py运行就好了
然后将User.py的server_ip改成自己的服务ip和端口
服务器打开的防火墙端口需要和客户端的一致
发消息时
0退出 1发送 内容
如:
1 在吗? (发送“在吗?”)
0 不用 (退出)
0 (退出)
网友评论