每5秒钟循环一次套接字请求(Python) [英] Loop socket request every 5 seconds (Python)
问题描述
我如何每5秒循环以下代码:
How would i loop every 5 seconds the following code :
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秒从服务器接收一次数据,我做了一段时间的True循环(lol),程序接口甚至没有加载,并且服务器被客户端淹没了.
I want a client to recieve data every 5 seconds from a server, i did a while True loop (lol) and the program interface didnt even load and the server got flooded by the client.
我只希望服务器使用存储在服务器上的变量每5秒更新一次客户端,而无需用户手动按下按钮.
I just want the server to update the client every 5 seconds with a variable that is stored on the server, without a user having to manually press a button.
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()
推荐答案
查看此问题:
您也可以使用after_idle
You can also use 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计划在GUI不再忙后调用的函数.您还可以使用.after(time,function)延迟特定的时间,然后再次调用该函数.
after_idle schedules a function the be called once the GUI isn't busy anymore. You can also use .after(time, function) to delay for a specific amount of time before calling the function again.
最后,您应该真正保持与服务器的连接,而不必每次都重新连接.
Finally, you should really maintain your connection to the server not reconnect each time.
这篇关于每5秒钟循环一次套接字请求(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!