Created
March 19, 2016 12:59
-
-
Save wuyongrui/e598d41027f361e7a8a6 to your computer and use it in GitHub Desktop.
the server to build ChatClient.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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