1.新建TXT 2.将服务器粘贴 3.保存,后缀改为.py 4.开始吧,相同操作粘贴客户端 服务器
import socket
import threading
import inspect
import ctypes
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 8000))
BANNED = []
def strhash(s: str) -> int:
h = 0
for i in range(len(s)):
h = (h * 31 + ord(s[i])) & 0xFFFFFF
return h
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread: threading.Thread):
_async_raise(thread.ident, SystemExit)
class Client:
def __init__(self, conn: socket.socket):
self.conn = conn
self.name = "Anonymous"
self.thread = threading.Thread(target=self.handle)
self.thread.start()
def handle(self):
while True:
try:
name = self.recv().decode()
for client in clients:
if client.name == name:
self.send('名称已被占用'.encode())
self.close()
return
if name in BANNED:
self.send('你已被 CCKick'.encode())
self.close()
return
else:
break
except UnicodeDecodeError:
self.send('名称不能包含特殊字符'.encode())
return
if '#' in name:
passcode, _, nick = name.partition('#')
passcode = hex(strhash(passcode))[2:]
name = f'{passcode} #{nick}'
else:
passcode = None
nick = name
self.name = name
self.nick = nick
self.send('欢迎加入聊天室!\n'.encode())
broadcast(f'\033[32m* {nick} 已连接\033[0m'.encode(), True)
while True:
try:
if name in BANNED:
self.send('\033[31m* 你已被 CCKick\033[0m'.encode())
self.close()
return
msg = self.recv()
if msg == b'\x00':
self.close()
break
if msg.startswith(b'/ban '):
_, _, banname = msg.partition(b' ')
if banname in BANNED:
self.send(f'\033[33m* {banname.decode()} 已经被 CCKick\033[0m'.encode())
else:
try:
banname = banname.decode()
BANNED.append(banname)
for client in clients:
if client.name == banname:
broadcast(f'\033[33m* {banname} 已被 {nick} CCKick\033[0m'.encode(), True)
client.close()
self.send(f'\033[33m* 执行 CCKick {banname} 成功 \033[0m'.encode())
break
else:
self.send(f'\033[33m* 名为 {banname} 的用户不在线\033[0m'.encode())
except UnicodeDecodeError:
self.send('指令使用格式错误,请查询使用文档'.encode())
elif passcode is not None:
broadcast(f'{passcode} \033[35m{nick}\033[0m: {msg.decode()}'.encode())
else:
broadcast(f'\033[35m{self.name}\033[0m: {msg.decode()}'.encode())
except UnicodeDecodeError:
self.send('消息不能包含特殊字符'.encode())
def send(self, msg: bytes):
try:
self.conn.send(msg)
except (ConnectionResetError, OSError):
self.close(False)
def close(self, halt=True):
if halt:
self.send(b'\x00')
self.conn.close()
clients.remove(self)
broadcast(f'\033[31m* {self.nick} 已退出\033[0m'.encode(), True)
stop_thread(self.thread)
def recv(self, buffer: int = 1024) -> bytes:
try:
return self.conn.recv(buffer)
except (ConnectionResetError, OSError):
self.close()
return b''
def broadcast(msg, pr=False):
for client in clients:
client.send(msg)
if pr:
print(msg.decode())
clients: list[Client] = []
if __name__ == '__main__':
import os; os.system('cls'); del os
sock.listen(5)
while True:
conn, addr = sock.accept()
client = Client(conn)
clients.append(client)
客户端
import os
import socket
import threading
import tkinter as tk
BUFFER_SIZE = 1024
def handle_input():
root.title('消息输入框')
root.protocol("WM_DELETE_WINDOW", lambda: None)
input_box = tk.Entry(root, width=50)
input_box.grid(row=0, column=0)
def send_message():
sock.send(input_box.get().encode())
input_box.delete(0, tk.END)
button = tk.Button(root, text='发送', command=send_message)
button.grid(row=0, column=1)
quit_button = tk.Button(root, text='退出', command=lambda: sock.send(b'\x00'))
quit_button.grid(row=0, column=3)
# set keybind enter to send message
root.bind('<Return>', lambda event: send_message())
root.mainloop()
def handle_receive():
while True:
data = sock.recv(BUFFER_SIZE).decode()
if data == '\x00':
root.destroy()
return
print(data)
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('172.17.43.27', 8000))
sock.send(input('请输入昵称: ').encode())
os.system('cls') # reset \033 usages
root = tk.Tk()
thread = threading.Thread(target=handle_receive, daemon=True)
thread.start()
handle_input()