I'm trying to get this simple python chat server up and running: http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server
It's working fine, except that I have to manually select a new port each time. Otherwise, I get an Error 98 saying that the port is already in use.
How to close a socket left open by a killed program? Recommended I use some SO_REUSEADDR: thing but I have no idea how to implement that into my barebones python program. Granted, I am a nub.
This page suggests doing some crazy autoselection but that sounds a bit more complicated than I need. http://twistedmatrix.com/pipermail/twisted-python/2005-August/011098.html
Thanks to anybody who can help me!
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()