Skip to content

Instantly share code, notes, and snippets.

@wuyongrui
Created March 19, 2016 12:59
Show Gist options
  • Select an option

  • Save wuyongrui/e598d41027f361e7a8a6 to your computer and use it in GitHub Desktop.

Select an option

Save wuyongrui/e598d41027f361e7a8a6 to your computer and use it in GitHub Desktop.
the server to build ChatClient.
# run server: $ sudo python server.py. sudo is neccessary
from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
class IphoneChat(Protocol):
def connectionMade(self):
self.factory.clients.append(self)
print "a client connected,clients are:",self.factory.clients
def connectionLost(self,reason):
print "a client lost connect"
self.factory.clients.remove(self)
# react to ChatEvent. anylyze the message and response
# the simple format of "msg:xx","iam:xx". in your own app, you can use json or other data
def dataReceived(self,data):
print "received data: ",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"
print msg
elif command == 'msg':
msg = self.name + ": " + content
print msg
for c in self.factory.clients:
c.message(msg)
# broadcast message . add '\n' is neccessary
def message(self,message):
self.transport.write(message + '\n')
#-------------------------------------------
factory = Factory()
factory.clients = []
factory.protocol = IphoneChat
reactor.listenTCP(8084,factory)
print "Iphone Chat server started"
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment