Reputation: 4311
I would like to write a UDP server in Python, which would have 3 different sockets listening on different ports at time. The main job of the server is to send clients a constant text, different for different socket.
I wrote the below code:
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()
But after I ran it it showed that:
/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
What is the problem?
Upvotes: 0
Views: 173
Reputation: 11
You are continually trying to re-start the sockets, as they fall under the never ending "while" loop. Remove the "while 1" and instead make your loop at the bottom of the script. could even be
if __name__ == "__main__":
run_server()
while 1:
time.sleep(1)
This way it will start your threads and then move on, in this case into a never ending sleep. Just as an example. Hope it helps.
Upvotes: 1