twisted python 服务器端口已被使用

twisted python server port already in use

(顺便用了一个mac)

我正在按照 this 构建扭曲 python 套接字服务器的教程进行操作,一切进展顺利。

我面临的一个问题是我不知道如何关闭服务器。基本上我更改了我的 python 脚本中的一些代码,我想重新启动服务器,但我不知道如何。我尝试从我的 activity 监视器中终止所有 python 进程,但是当我再次尝试 运行 服务器时,我收到服务器无法侦听端口 80 的错误。

这是脚本:

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.

使用netstat -nlp | grep 80查找使用80端口的进程

如果可能,使用kill -9 pid终止进程。

或者您可以使用其他端口,例如 12345。

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