Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - The loop gods strike again - How to keep socket connected despite GUI mainloop?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...