在 Python 中使用该select.select()
方法时,有没有办法使用来自 GUI(Tkinter 条目)的输入从套接字发送数据?
select() 的输入列表接受 sys.stdin 或从服务器接收的数据,但无论如何要从 GUI 获取数据并将其发送出去?或者选择不能与 GUI 一起使用?
我已经进行了广泛的搜索,但是如果您有指向另一个线程的链接,我也将不胜感激。
import socket, select, threading, Queue, cPickle
from Tkinter import *
from Message import *
class GUI(Frame):
def __init__(self, host="localhost",port=5678, root="Tk()"):
Frame.__init__(self,root)
self.nickname = raw_input("What is your screen name? ")
self.inqueue = Queue.Queue()
self.outqueue = Queue.Queue()
self.root = root
self.text = Text(self,height=10,width=40)
self.scroll=Scrollbar(self)
self.text.configure(yscrollcommand=self.scroll.set)
self.scroll.grid(row=0, column=1, sticky=N+S)
self.scroll.config(command=self.text.yview)
self.text.grid(row=0,column=0)
self.entry = Entry(self)
self.entry.grid(row=1,column=0)
self.pack()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.sock.send(self.nickname)
self.thread1=threading.Thread(target=self.cmdloop)
self.thread1.start()
self.entry.bind("<Return>",self.enter)
self.call()
def enter(self,event):
msg = Message(self.nickname,0,self.entry.get())
self.entry.delete(0, END)
msg = cPickle.dumps(msg)
self.inqueue.put(msg)
self.sock.send(msg)
def call(self):
self.processData()
self.after(100,self.call)
def cmdloop(self):
while 1:
sys.stdout.flush()
# Wait for input from stdin & socket
inputs, outputs, excepts = select.select([0,self.sock],[],[])
for i in inputs:
if i == 0:
data = sys.stdin.readline()
msg = Message(self.nickname,0,data)
msg = cPickle.dumps(msg)
self.inqueue.put(msg)
self.sock.send(msg)
elif i == self.sock:
data = self.sock.recv(1024)
self.inqueue.put(data)
def processData(self):
while self.inqueue.qsize():
try:
msg = self.inqueue.get(0)
msg = cPickle.loads(msg)
self.text.insert(END, msg.getusr()+": "+msg.getmsg())
self.text.yview(END)
except Queue.Empty:
pass
if __name__ == "__main__":
root = Tk()
root.title("textarea")
client = GUI(sys.argv[1],int(sys.argv[2]),root)
root.mainloop()