【发布时间】:2011-05-30 01:36:55
【问题描述】:
我将如何每 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 循环(大声笑),程序界面甚至没有加载,服务器被客户端淹没了。
我只希望服务器每 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()
【问题讨论】:
-
你为什么觉得有必要在中间随机插入(lol)?
-
这个问题的答案取决于您如何创建程序界面。你用什么 wxPython、PyQt、PySide、curses、Gtk?
-
因为我知道 True 绝对不是正确做某事的正确方法。我还使用 tkinter 制作了 GUI。
-
(lol) 在我看来让你看起来很傻。如果你不这样做,我至少会更认真地对待问题。