address already in use with multithreaded server in twisted
I'm trying to write a multithreaded server in python using twisted. callInThread(self.task) is to create a new thread to run task() every time a client requests sth from the server. When the client sends requests one by one(all through port 53), everything works but when there are multiple requests at the same time, it says
File "", line 1, in bind socket.error: [Errno 98] Address already in use
Is there sth wrong with my threads, only one can use the port at a time? If so, how am I supposed to go about with multithreading my server? Thanks a lot!
class BaseThreadedUDPServer(DatagramProtocol):
def datagramReceived(self, datagram, (host, port)):
print "received %r from %s:%d" % (datagram, host, port)
reactor.callInThread(self.task)
def task(a):
print "wa开发者_开发问答iting on port:", csport
while 1:
## RCV QUERY ##
query, addr = csSocket.recvfrom(csbuf)
## GET ANS ##
ans = socket.gethostbyname(query)
## SEND ANS ##
scSocket.sendto(ans, scaddr)
def main():
print "main"
reactor.listenUDP(53, BaseThreadedUDPServer())
reactor.run()
You don't need threads. This is horribly buggy. Twisted is already calling recv
for you: and it is the result of that which is passed to datagramReceived
. Don't call it again yourself. You don't need a thread.
However, that probably has nothing to do with your problem. 53 is the default DNS port: the problem you have is that another server, probably a DNS server is already running on that computer. Try changing 53 to some other value.
But I'm not really sure; in the future, please paste a full traceback. That traceback line obviously didn't come from the example that you've pasted, since there's nothing on line 1 except a 'class' statement. Also, since this code is indented wrong and raises a SyntaxError
, it's obviously not exactly the same as what you're running.
Assuming you are actually doing something with DNS, Twisted has its own DNS server; you should be using twisted.names
rather than implementing your own DNS packet parsing.
精彩评论