介绍一款很帅的插件AutobahnPython,通过它可以在python中很方便的使用websocket进行通信(基于twisted框架)。
这个插件真正强大的地方是它提供了一个 发布/订阅模式,具体内容有空再写,先简单介绍一下如何建立传统的连接。
下载地址:http://autobahn.ws/python/downloads
建立服务器:
# 必须的模块
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
# 继承WebSocketServerProtocol类
class MyServerProtocol(WebSocketServerProtocol):
# 建立websocket时调用的函数
def onOpen(self):
print "open"
# websocket关闭时调用的函数,其中wasClean指示是否正常关闭,code指示关闭状态,reason指示原因
def onClose(self, wasClean, code, reason):
print "close"
# 收到消息后的处理函数,其中binary指示是字符串形式还是二进制
def onMessage(self, msg, binary):
print msg
# 发送消息,binary意义同上
self.sendMessage(msg, bi