我如何每5秒循环一次下面的代码:
sendSocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sendSocket.connect ( ( 'CENSORED', 1234 ) )
sendSocket.send ( 'request posit' )
data = sendSocket.recv( 100 )
chatLog.insert(END, data)
我想让客户端每5秒从服务器接收一次数据,我做了一个while True循环(lol),程序接口甚至都没有加载,服务器被客户端淹没了。
我只希望服务器使用存储在服务器上的变量每5秒更新一次客户端,而不需要用户手动按下按钮。
import socket, time
from Tkinter import *
## Main Window
gui = Tk()
gui.geometry('450x350-5+40')
gui.minsize(450,350)
gui.maxsize(450,350)
userInput = StringVar()
## Main window that displays user and server input.
chatLog = Text(gui, width=60, height=15)
chatLog.pack()
## Send Packet function, main part of the script. Sends whatever the user puts in.
def sendChat():
sendSocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sendSocket.connect ( ( 'nope.com', 1234 ) )
sendSocket.send ( e.get() )
data = sendSocket.recv( 100 )
chatLog.insert(END, data)
sendSocket.close()
while True:
sendSocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sendSocket.connect ( ( 'nope.com', 1234 ) )
sendSocket.send ( 'request posit' )
data = sendSocket.recv( 100 )
chatLog.insert(END, data)
sendSocket.close()
time.sleep (5.0)
## Submit text button
b = Button(gui, text="Send", command=sendChat )
b.pack()
## Text entry box
e = Entry(gui, textvariable=userInput)
e.pack()
gui.mainloop()
发布于 2011-05-30 10:04:02
请参阅此问题:
How to make tkinter repond events while waiting socket data?
您也可以使用after_idle
def read_the_socket():
sendSocket.send ( 'request posit' )
data = sendSocket.recv( 100 )
gui.after(5000, read_the_socket)
gui.after_idle(read_the_socket)
after_idle计划在图形用户界面不再繁忙时调用一个函数。您还可以使用.after( time,function)在再次调用函数之前延迟一段特定的时间。
最后,您应该真正维护与服务器的连接,而不是每次都重新连接。
发布于 2011-05-30 09:42:51
import time
while True:
do_stuff ()
time.sleep (5.0)
理想情况下,在do_stuff up之后,你会计算你已经睡了多长时间,然后适当地调整你的睡眠时间,以恢复同步。
编辑:假设这就是你正在做的所有事情。否则,使用时间函数来查看是否已经过了5秒。time.localtime()
之类的。我不记得它们的名字了,但是python的lib有很好的文档记录。
编辑2:尽管这可能不适用于tkinter。实际上,如果完整的代码和tkinter已经在原始消息中,我就不会发布。抱歉的!
https://stackoverflow.com/questions/6171578
复制相似问题