【问题标题】:Socket and threads python套接字和线程python
【发布时间】:2014-05-15 16:10:49
【问题描述】:

我只是在试验这个。每当用户打开程序时,他都应该“在线”并监听连接。
GUI 在这里被加载。

class AppUI(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUi()

    def initUi(self):
        self.parent.title("Redux")
        self.pack(fill=BOTH, expand=1)
        self.initMenu()
        self.initAudio()
        self.initMidi()
        self.initBroadcast()
        self.initFriendList()

但每当我将我的线程代码粘贴到initUi 下时,它就会在加载时卡住,并且我的 GUI 不会显示。 (继续加载,因为线程正在监听连接)

thread2 = threading.Thread(target=Connection().getOnline("", 50007))
thread2.start()

Class Connection():
    def getOnline(self, host, port):
        self.s.bind((host, port))
        self.s.listen(2)
        print('Now online - listening to connections')
        conn, addr = self.s.accept()
        print("Connected to:", addr)

为什么我的线程不起作用?

【问题讨论】:

    标签: python multithreading sockets


    【解决方案1】:

    你的问题出在这一行:

    thread2 = threading.Thread(target=Connection().getOnline("", 50007))
    

    在这里,您实际上是在 调用 Connection().getOnline("", 50007),它会阻塞。您还没有在后台执行此操作,而是在您的线程启动之前完成了。您需要将调用调整为如下所示:

    thread2 = threading.Thread(target=Connection().getOnline, args = ("", 50007))
    

    【讨论】:

    • 呸太快了...(+1 你打败了我...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 2019-04-24
    • 2011-02-11
    • 2013-04-02
    • 2015-05-21
    • 1970-01-01
    相关资源
    最近更新 更多