The loop gods strike again - How to keep socket co

2020-02-14 08:45发布

问题:

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!

回答1:

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()


回答2:

You might want to use Twisted http://twistedmatrix.com/trac/

It integrates Tk loop into its reactor loop(which does the networking)http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.tksupport.html ,and you can easily build protocols....



回答3:

Run them in separate threads. See the threading module documentation for more information.