Search code examples
pythoniossocketsnetwork-programmingtwisted

Python / Twisted "NameError: name 'Protocol' is not defined"


I was following a pretty basic tutorial for building a Python socket server with Twisted.

This is my code:

from twisted.internet.protocol import Factory
from twisted.internet import reactor

class IphoneChat(Protocol):
def connectionMade(self):
    print "a client connected"

factory = Factory()
factory.protocol = IphoneChat
reactor.listenTCP(80, factory)
print "iPhone Chat server started"
reactor.run()

I named the file server.py and saved it as a plain text file on my desktop. I then opened terminal (I'm running Mac OS X 10.7.4) and changed directories to Desktop, then executed the file with "sudo python server.py". I have tried to import various libraries to no prevail, and the other nameerrors I've found on this website and around the internet for python don't involve twisted (as far as I can tell, I'm a stone cold beginner).

I was only following this tutorial.


Solution

  • You are inheriting from Protocol but didn't import it. Add it to your import statement.

    from twisted.internet.protocol import Factory, Protocol