我想在Python中编写一个UDP服务器,它将有3个不同的套接字在不同的端口上监听。服务器的主要工作是向客户端发送一个不同的文本,不同的套接字。
我写了下面的代码:
import socket
import thread
def create_socket_server(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
return s
def run_socket(s, secret):
while True:
(data, addr) = s.recvfrom(1024)
s.sendto(secret, addr)
def run_server():
s1 = create_socket_server('127.0.0.1', 2000)
s2 = create_socket_server('127.0.0.1', 3000)
s3 = create_socket_server('127.0.0.1', 4000)
while 1:
thread.start_new_thread(run_socket, (s1, "A"))
thread.start_new_thread(run_socket, (s2, "B"))
thread.start_new_thread(run_socket, (s3, "C"))
if __name__ == "__main__":
run_server()
但在我跑完之后它显示出:
/usr/bin/python2.7 /home/brian/Temp/udp.py
Traceback (most recent call last):
File "/home/brian/Temp/udp.py", line 29, in <module>
run_server()
File "/home/brian/Temp/udp.py", line 24, in run_server
thread.start_new_thread(run_socket, (s2, "SI"))
thread.error: can't start new thread
Process finished with exit code 1
有什么问题?
答案 0 :(得分:1)
你不断尝试重新启动套接字,因为它们属于永无止境的“while”循环。删除“while 1”,然后将循环放在脚本的底部。甚至可能是
if __name__ == "__main__":
run_server()
while 1:
time.sleep(1)
这样它会启动你的线程,然后继续前进,在这种情况下进入一个永无止境的睡眠。仅作为一个例子。希望它有所帮助。