在扭曲的python上重用TCP端口

时间:2012-08-10 22:39:17

标签: python sockets port twisted

我正在尝试启动并运行这个简单的python聊天服务器: http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server

它工作正常,但我必须每次都手动选择一个新端口。否则,我得到一个错误98,说该端口已被使用。

How to close a socket left open by a killed program? 建议我使用一些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()

0 个答案:

没有答案