【问题标题】:twisted python server port already in use扭曲的 python 服务器端口已在使用中
【发布时间】:2015-07-31 23:37:00
【问题描述】:

(顺便用mac)

我正在关注 this 构建一个扭曲的 python 套接字服务器的教程,一切都很好。

我面临的一个问题是我不知道如何关闭服务器。基本上我在我的python脚本中更改了一些代码,我想重新启动服务器,但我不知道如何。我尝试从我的活动监视器中杀死所有 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(最近一次调用最后一次): 文件“pythonSocketServer.py”,第 39 行,在 reactor.listenTCP(80,工厂) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/posixbase.py”,第495行,在listenTCP p.startListening() 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/tcp.py”,第 980 行,在 startListening 引发无法监听错误(self.interface,self.port,le) twisted.internet.error.CannotListenError:无法监听任何内容:80:[Errno 48] 地址已在使用中。

【问题讨论】:

  • 尝试使用 > 1000 的端口号,例如 8080
  • @BrentWashburne 如果我不断更改它的工作端口,但是在我停止/重新启动服务器后如何让它在同一个端口上工作?
  • 也许您的网络服务器正在使用端口 80?
  • @BrentWashburne 是,但我把它关掉了

标签: python sockets twisted


【解决方案1】:

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

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

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

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

【讨论】:

  • 在 Mac 上,尝试lsof -n TCP:$PORT | grep LISTEN (stackoverflow.com/questions/4421633/…)。在 mac 上,-p 需要一个协议作为参数
  • Cleaner 仍然是 lsof -iTCP -sTCP:LISTEN,它在 Linux 和 Mac 上都可以正常工作。
  • 或者,如果您知道要查找的确切端口,lsof -n -iTCP:$PORT -sTCP:LISTEN
猜你喜欢
  • 1970-01-01
  • 2011-03-04
  • 2012-08-08
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
  • 2011-09-23
相关资源
最近更新 更多