twisted python server port already in use

2019-09-14 13:42发布

问题:

(using a mac by the way)

I'm following this tutorial for building a twisted python socket server and everything is going great.

the one issue I'm facing is I don't know how to turn off the server. Basically I changed some code in my python script and I'd like to restart the server but I don't know how. I tried killing all python processes from my activity monitor, but when I try to run the server again, I get an error that the server can't listen on port 80.

here's the script:

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor

class IphoneChat(Protocol):
    def connectionMade(self):
        self.factory.clients.append(self)
        print "clients are ", self.factory.clients

    def connectionLost(self, reason):
        self.factory.clients.remove(self)

    def dataReceived(self, data):
        a = data.split(':')
        print a
        if len(a) > 1:
            command = a[0]
            content = a[1]

            msg = ""
            if command == "iam":
                self.name = content
                msg = self.name + " has joined"

            elif command == "msg":
                msg = self.name + ": " + content
                print msg

            for c in self.factory.clients:
                c.message(msg)
    def message(self, message):
        self.transport.write(message + '\n')

factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(80, factory)
print "Iphone Chat server started"
reactor.run()

Traceback (most recent call last): File "pythonSocketServer.py", line 39, in reactor.listenTCP(80, factory) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/posixbase.py", line 495, in listenTCP p.startListening() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/tcp.py", line 980, in startListening raise CannotListenError(self.interface, self.port, le) twisted.internet.error.CannotListenError: Couldn't listen on any:80: [Errno 48] Address already in use.

回答1:

Use netstat -nlp | grep 80 to find the process using the port 80.

Kill the process if possible by using kill -9 pid.

Or you can use another port like 12345.

factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(12345, factory)