我正在尝试启动并运行这个简单的 python 聊天服务器: http ://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server
它工作正常,除了我每次都必须手动选择一个新端口。否则,我会收到错误 98,说明该端口已在使用中。
如何关闭被杀死的程序打开的套接字? 推荐我使用一些 SO_REUSEADDR: 东西,但我不知道如何在我的准系统 python 程序中实现它。诚然,我是个小胖子。
这个页面建议做一些疯狂的自动选择,但这听起来比我需要的要复杂一些。 http://twistedmatrix.com/pipermail/twisted-python/2005-August/011098.html
感谢任何可以帮助我的人!
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class IphoneChat(Protocol):
def connectionMade(self):
#self.transport.write("""connected""")
self.factory.clients.append(self)
print "clients are ", self.factory.clients
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
#print "data is ", data
a = data.split(':')
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()