有没有办法限制客户端在Python聊天室应用程序中每秒发送的消息数



我正在为学校制作一个python聊天室应用程序,该应用程序具有正常运行的客户端和服务器端脚本。我现在正在聊天室中添加多种功能,使其更易于使用,其中之一有望成为垃圾邮件保护。有没有一种方法可以记录客户端在某一特定测量时间内发送的消息数量,如果超过最大值,则在一定时间内静音?

clientside.py:

from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter as tkinter
#import tkinter.ttk as ttk
#from ttkthemes import ThemedStyle
from tkinter import END
from datetime import *
import time as tme
def receive():
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
msg_list.insert(tkinter.END, '[' + current_time + '] ' + msg)
msg_list.yview(END)
msg_list.yview()
except OSError:
break
def send(event=None):
msg = my_msg.get()
if msg.isspace() != True:
my_msg.set("")
client_socket.send(bytes(msg, "utf8"))
msg_list.yview(END)
msg_list.yview()
elif msg.isspace() == True:
my_msg.set("")
if msg == "{quit}":
client_socket.close()
top.quit()
def on_closing(event=None):
top.destroy()
my_msg.set("{quit}")
send()
top.quit()
top = tkinter.Tk()
top.resizable(width=False, height=False)
#top.iconbitmap('C:/Users/Ethen Dixon/Downloads/filled_chat_aH2_icon.ico')
top.title("Chat Room 90")
#style = ThemedStyle(top)
#style.set_theme("equilux")
messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar()
my_msg.set("[type here]")
scrollbar = tkinter.Scrollbar(messages_frame)
msg_list = tkinter.Listbox(messages_frame, height=30, width=100, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()
entry_field = tkinter.Entry(top, textvariable=my_msg, width=100)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
top.protocol("WM_DELETE_WINDOW", on_closing)
HOST = input('Enter host: ')
PORT = input('Enter port: ')
if not PORT:
PORT = 33000
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
tkinter.mainloop()

serverside.py:

from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("Welcome to Chat Room 90! Please type in your username and press enter.", "utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
def handle_client(client):
"""Handles a single client connection."""
name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s!' % name
client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
broadcast(msg, name+": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break
def broadcast(msg, prefix=""):
"""Broadcasts a message to all the clients."""
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
clients = {}
addresses = {}
HOST = ''
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()

实现这一点的一种方法是使用widget.unbind(sequence, funcid = None)方法。顾名思义,这将删除w上已确定事件的绑定。

然后,您可以使用tkinter内置方法root.after()来调用您创建的函数,以将按钮重新绑定到该函数。

但是,要实现这一点,您需要使用.bind()方法绑定send_button。


def rebind():
send_button.bind("<Button-1>", send)

send_button.bind("<Button-1>", send)
send_button.unbind("<Button-1>", funcid=None) 
top.after(time in miliseconds, rebind)

最新更新