新一代极简聊天室——FireTalk
fire_star_AFO · · 科技·工程
由于我看见的其它聊天室机房的人都不会用,我便用Python做了一个极简聊天室——FireTalk。
:::info[下面是 chat.py]
import socket
import threading
import sys
CURRENT_STYLE = "style_one"
STYLE_MAP = {
"style_one": ("▁▏▕▔", " "),
"style_two": ("━||━", " ")
}
HOST = '0.0.0.0'
PORT = 9999
client_sockets = []
lock = threading.Lock()
def print_with_style(content):
frame_chars = STYLE_MAP.get(CURRENT_STYLE, STYLE_MAP["style_one"])
top_char, left_char, right_char, bottom_char = frame_chars[0]
padding = frame_chars[1]
content_len = len(content) + len(padding) * 2
top_bottom = top_char * content_len
middle = f"{left_char}{padding}{content}{padding}{right_char}"
print(top_bottom)
print(middle)
print(bottom_char * content_len)
def handle_client(client_socket, client_addr):
print_with_style(f" 新用户加入FireTalk:{client_addr[0]}:{client_addr[1]}")
try:
while True:
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
if data.strip() in ["style_one", "style_two"]:
global CURRENT_STYLE
CURRENT_STYLE = data.strip()
client_socket.send(f" 样式已切换为:{CURRENT_STYLE}".encode('utf-8'))
continue
msg = f"️ {client_addr[0]}:{client_addr[1]}:{data}"
print_with_style(msg)
with lock:
for sock in client_sockets:
if sock != client_socket:
sock.send(msg.encode('utf-8'))
except Exception as e:
print_with_style(f" FireTalk用户{client_addr}异常:{str(e)}")
finally:
with lock:
client_sockets.remove(client_socket)
client_socket.close()
print_with_style(f" FireTalk用户{client_addr}已退出")
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print_with_style(f" FireTalk聊天室已启动 | 地址:{HOST}:{PORT} | Python3.10")
print_with_style(" 指令说明:style_one(白色外框) | style_two(黑色外框)")
try:
while True:
client_socket, client_addr = server_socket.accept()
with lock:
client_sockets.append(client_socket)
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_addr))
client_thread.daemon = True
client_thread.start()
except KeyboardInterrupt:
print_with_style("\n FireTalk聊天室正在关闭...")
with lock:
for sock in client_sockets:
sock.close()
server_socket.close()
sys.exit(0)
def client_send_msg(client_socket):
global CURRENT_STYLE
while True:
try:
msg = input("")
if not msg:
continue
if msg.strip() in ["style_one", "style_two"]:
CURRENT_STYLE = msg.strip()
client_socket.send(msg.encode('utf-8'))
print_with_style(f" 本地样式已切换为:{CURRENT_STYLE}")
continue
client_socket.send(msg.encode('utf-8'))
except Exception as e:
print_with_style(f" FireTalk发送失败:{str(e)}")
client_socket.close()
sys.exit(1)
def client_recv_msg(client_socket):
while True:
try:
data = client_socket.recv(1024).decode('utf-8')
if not data:
print_with_style(" 与FireTalk服务器断开连接")
client_socket.close()
sys.exit(1)
print_with_style(data)
print("> ", end="", flush=True)
except Exception as e:
print_with_style(f" FireTalk接收失败:{str(e)}")
client_socket.close()
sys.exit(1)
def start_client(server_ip):
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.settimeout(5)
client_socket.connect((server_ip, PORT))
client_socket.settimeout(None)
print_with_style(" 成功加入FireTalk公共聊天室!")
print_with_style(" 指令说明:style_one(白色外框) | style_two(黑色外框)")
print("> ", end="", flush=True)
send_thread = threading.Thread(target=client_send_msg, args=(client_socket,))
recv_thread = threading.Thread(target=client_recv_msg, args=(client_socket,))
send_thread.daemon = True
recv_thread.daemon = True
send_thread.start()
recv_thread.start()
send_thread.join()
recv_thread.join()
except socket.timeout:
print_with_style("连接FireTalk超时:服务端未启动或IP错误")
sys.exit(1)
except ConnectionRefusedError:
print_with_style("连接FireTalk被拒绝:服务端未启动或端口错误")
sys.exit(1)
except KeyboardInterrupt:
print_with_style("\n退出FireTalk聊天室")
client_socket.close()
sys.exit(0)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("FireTalk使用方法:")
print(" 启动服务端:python chat.py server")
print(" 启动客户端:python chat.py client [服务端IP] (例:python chat.py client 127.0.0.1)")
sys.exit(1)
mode = sys.argv[1].lower()
if mode == "server":
start_server()
elif mode == "client":
if len(sys.argv) < 3:
print(" FireTalk客户端需指定服务端IP,例:python chat.py client 127.0.0.1")
sys.exit(1)
start_client(sys.argv[2])
else:
print(" FireTalk无效模式,仅支持 server / client")
sys.exit(1)
:::
使用方法:
将 chat.py 保存后放在桌面(一定要命名为 chat.py,一定要放在桌面),然后打开 cmd。输入 cd Desktop,再输入 python chat.py server。
随后将这个页面最小化。
再打开一个 cmd。在这个 cmd 中输入 cd Desktop。随后再输入 python chat.py client 127.0.0.1(IP 脆弱)。这样就建了一个客户端。
想要进多少个人,就建几个客户端。
如果要退出,在客户端按 Ctrl + C。关闭房间则在第一个 cmd 按 Ctrl + C。
页面有些丑陋,但易上手。
展示图:
感谢大家使用。