Lau*_*ird 4 python multithreading udp
我最近一直在研究一个程序(正如你可能从我之前提出的问题中看到的那样)而且我在理解和实现多线程方面遇到了麻烦.
我按照教程(二进制潮汐)来设置UDP服务器,效果很好.然而,我遇到的问题是,当我在新线程上创建阻塞UDP套接字时,我在主程序中最初创建线程的代码不起作用.这是我的一些代码:
main.py:
from thread import*
import connections
start_new_thread(networkStart.startConnecton())
print 'This should print!'
Run Code Online (Sandbox Code Playgroud)
networkStart.py:
def startConnecton():
userData.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
userData.s.bind((HOST, PORT))
except socket.error, msg:
print 'Bind failed. Error code: ' +str(msg[0]) + 'Message' +msg[1]
sys.exit()
print 'Socket bind complete'
userData.s.listen(10)
# Set the socket to listening mode, if there are more than 10 connections waiting reject the rest
print 'Socket now listening'
#Function for handling connections. Each new connection is handled on a separate thread
start_new_thread(connections.connectionListen())
Run Code Online (Sandbox Code Playgroud)
connections.py:
def connectionListen():
while 1:
print 'waiting for connection'
#wait to accept a connection - blocking call
conn, addr = userData.s.accept()
userData.clients += 1
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments
start_new_thread(users.clientthread ,(conn, userData.clients))
Run Code Online (Sandbox Code Playgroud)
我基本上只是希望能够在新线程上调用startConnection函数后在main.py中执行任何代码(即,在此实例中打印字符串).
我已经在这个程序上苦苦挣扎了很长一段时间,Python对我来说是新手,我发现它非常具有挑战性.我假设我必须在我实现多线程的方式上犯一些错误,任何帮助都会非常感激!
start_new_thread
接收函数和参数列表,但您直接使用函数调用:start_new_thread(networkStart.startConnecton())
.
但是,我建议你使用threading
模块(官方文档这样做),它具有更高的抽象级别.
import threading
import connections
threading.Thread(target=networkStart.startConnecton).start()
print 'This should print!'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
408 次 |
最近记录: |