0

(using a mac by the way)

I'm following this tutorial for building a twisted python socket server and everything is going great.

the one issue I'm facing is I don't know how to turn off the server. Basically I changed some code in my python script and I'd like to restart the server but I don't know how. I tried killing all python processes from my activity monitor, but when I try to run the server again, I get an error that the server can't listen on port 80.

here's the script:

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.

duxfox--
  • 8,314
  • 13
  • 50
  • 112

1 Answers1

1

Use netstat -nlp | grep 80 to find the process using the port 80.

Kill the process if possible by using kill -9 pid.

Or you can use another port like 12345.

factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(12345, factory)
luoluo
  • 4,833
  • 2
  • 25
  • 38
  • On mac, try `lsof -n TCP:$PORT | grep LISTEN` (http://stackoverflow.com/questions/4421633/who-is-listening-on-a-given-tcp-port-on-mac-os-x). On mac, -p requires a protocol as an argument – awmo Aug 01 '15 at 00:42
  • Cleaner still is `lsof -iTCP -sTCP:LISTEN`, which works fine on both Linux and Mac. – Glyph Aug 01 '15 at 01:01
  • Or, if you know the exact port you're looking for, `lsof -n -iTCP:$PORT -sTCP:LISTEN`. – Glyph Aug 01 '15 at 01:02