循环神再次袭击 - 如何保持插座连接尽管GUI mainloop? [英] The loop gods strike again - How to keep socket connected despite GUI mainloop?

查看:222
本文介绍了循环神再次袭击 - 如何保持插座连接尽管GUI mainloop?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题



如何运行Tkinter mainloop 同时,在同一个脚本?



背景



我正在Tkinter中创建GUI服务器( Python 2.7.3 )。到目前为止,GUI工作正常,服务器正常工作,但我有问题集成两者。据我所知(纠正我,如果我错了)服务器需要运行在无限循环接受新用户。可悲的是,GUI还需要一个无限循环。我想知道如何让两个循环同时运行。



我当前的mainloop函数看起来像这样( s 是套接字对象):

  def mainloop:
while True:
channel, addr = s.accept()
printConnected with,addr

需要保持服务器运行(我想。)问题是,这个循环在我的 mainloop 之前,因此我有问题。



完整代码



我的服务器代码是此处,我的客户端是此处



谢谢!

解决方案

使用线程模块打开服务器

替换

  mainloop 

  thread.start_new_thread(mainloop,(s,))



根据A. Rodas的注释,最好使用与Python 3兼容的更新的 threading 模块。



以便您可以替换

  mainloop 

  Thread(target = mainloop,args =(s,))。start()


Question

How to run the Tkinter mainloop and an infinite server loop simultaneously, in the same script?

Background

I am in the process of creating a GUI server in Tkinter (Python 2.7.3). So far, the GUI works correctly, the Server works correctly, but I am having issues integrating the two. As far as I know (correct me if I am wrong) the server needs to be running on an infinite loop to accept new users. Sadly, the GUI also needs an infinite loop. I am wondering how to have both loops running at the same time.

My current mainloop function looks like this (s is the socket object):

def mainloop(s):
    while True:
        channel, addr = s.accept()
        print "Connected with", addr

That is obviously needed to keep the server running (I think.) The issue though, is that this loop comes before my mainloop and thus I have problems with that. If I do it the other way around, the Server is never opened.

Full Code

My server code is here, and my client is here.

Thanks!

解决方案

Use the thread module to open your server mainloop in a new thread.

Replace

mainloop(s)

with

thread.start_new_thread(mainloop, (s,))

Then you can call root.mainloop() to run Tkinter, just like you did.


UPDATE

Per A. Rodas' comment below, it's preferred to use the newer threading module which is compatible with Python 3.

so you can replace

mainloop(s)

with

threading.Thread(target=mainloop, args=(s,)).start()

这篇关于循环神再次袭击 - 如何保持插座连接尽管GUI mainloop?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆