【问题标题】:How can I manage to wait on my socket connexion without blocking the program?如何在不阻塞程序的情况下设法等待我的套接字连接?
【发布时间】:2019-06-19 03:16:48
【问题描述】:

我使用客户端-服务器套接字连接从我的 Python 服务器传输一些数据。我目前遇到的问题是服务器套接字的创建阻塞了程序,因为它无法连接到客户端。

我尝试使用异步但没有成功

from flask import *
import random   
import socket
import json  
app = Flask(__name__, static_url_path='')
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('',55555))

async def acceptConnexion():
    while True:
        socket.listen(10)
        client, address = socket.accept()
        print("{} connected".format( address ))

@app.route('/getInfos')
def getInfos():
    global infosThymio
    return json.dumps(infosThymio)

if __name__ == '__main__':
    app.run()

我不知道在哪里可以调用我的 acceptConnexion() 并且我不知道如何设法让这个方法在后台运行,直到它可以与客户端进行连接。

【问题讨论】:

  • 可能在单独的任务/线程中运行acceptConnexion
  • select 可以在侦听套接字和其他套接字上等待,并且可以设置超时。不确定此处是否相关,因此仅作为评论发布。

标签: python sockets asynchronous flask server


【解决方案1】:

您可以将accept 调用分离到一个单独的线程,这样可以让主线程继续,而侧线程等待接受。

import socket
from threading import Thread

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('',55555))

def acceptConnexion():
    print("running in thread")
    while True:
        socket.listen(10)
        address = socket.accept()
        print("{} connected".format( address ))    

if __name__ == "__main__":
    thread = Thread(target = acceptConnexion)
    print("you can here do bla bla")
    x = 1
    print("x", x)
    print("Main thread will wait here for thread to exit")
    thread.join()
    print("thread finished...exiting")

【讨论】:

  • 非常感谢您的意见。它就像一个魅力!
猜你喜欢
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
相关资源
最近更新 更多