TwistedFa 2014-11-08
python2.7.8可用,python2.6一样的代码就有问题
https://github.com/tavendo/AutobahnPython/
gitclonehttps://github.com/tavendo/AutobahnPython.git
为了不污染python的系统环境
假设我的当前目录是
/data/mysocket/python/
virtualenv twisted cd twisted/ source bin/activate echo $VIRTUAL_ENV echo $PATH 进入 python setup.py install pip install zope.interface yum install libffi-devel yum install bzip2-devel 安装twisted 这里可能会报错 bz2模块找不到之类的 参考http://stackoverflow.com/questions/8115280/importerror-no-module-named-bz2-for-python-2-7-2 先 把动态库copy到2.7的 cp /usr/lib64/python2.6/lib-dynload/bz2.so /data/mysocket/python/twisted/lib/python2.7/ pip install twisted cd AutobahnPython\examples\twisted\websocket\echo> python server.py
在windows中安装:
先安装virtualenv
从
https://pypi.python.org/pypi/virtualenv#downloads
下载
virtualenv-1.11.6.tar.gz
python setup.py install 在python/Scripts中多了virtualenv.exe virtualevn twist cd twist Scripts/activate.bat pip install zope.interface pip install twisted (twist) D:\pythonwork\AutobahnPython\examples\twisted\websocket\echo>python serv er.py 2014-11-08 20:45:22+0800 [-] Log opened. 2014-11-08 20:45:22+0800 [-] WebSocketServerFactory starting on 9000 2014-11-08 20:45:22+0800 [-] Starting factory <autobahn.twisted.websocket.WebSoc ketServerFactory instance at 0x0000000002BBF288>
然后打开
AutobahnPython/examples/twisted/websocket/echo/client.html
F12查看helloworld吧
twisted入门
http://outofmemory.cn/code-snippet/4624/python-twisted-example#6762184-tsina-1-61743-3400cac556b7c64aaad138f696c2c997
广播的例子修改如下
(mysite)[root@broadcast broadcast]# cat server.py ############################################################################### ## ## Copyright (C) 2011-2013 Tavendo GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### import sys from twisted.internet import reactor from twisted.python import log from twisted.web.server import Site from twisted.web.static import File import time from autobahn.twisted.websocket import WebSocketServerFactory, \ WebSocketServerProtocol, \ listenWS class BroadcastServerProtocol(WebSocketServerProtocol): def onOpen(self): self.factory.register(self) msg="open "+str(time.time()) print msg self.sendMessage(msg.encode('utf8')) def onMessage(self, payload, isBinary): if not isBinary: #msg = "{} from {}".format(payload.decode('utf8'), self.peer) #self.factory.broadcast(msg) self.factory.broadcast(payload) def connectionLost(self, reason): WebSocketServerProtocol.connectionLost(self, reason) self.factory.unregister(self) class BroadcastServerFactory(WebSocketServerFactory): """ Simple broadcast server broadcasting any message it receives to all currently connected clients. """ def __init__(self, url, debug = False, debugCodePaths = False): WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths) self.clients = [] #self.tickcount = 0 #self.tick() def tick(self): self.tickcount += 1 self.broadcast("tick %d from server" % self.tickcount) reactor.callLater(1, self.tick) def register(self, client): if not client in self.clients: print("registered client {}".format(client.peer)) self.clients.append(client) def unregister(self, client): if client in self.clients: print("unregistered client {}".format(client.peer)) self.clients.remove(client) def broadcast(self, msg): print("broadcasting message '{}' ..".format(msg)) for c in self.clients: c.sendMessage(msg.encode('utf8')) print("message sent to {}".format(c.peer)) class BroadcastPreparedServerFactory(BroadcastServerFactory): """ Functionally same as above, but optimized broadcast using prepareMessage and sendPreparedMessage. """ def broadcast(self, msg): print("broadcasting prepared message '{}' ..".format(msg)) preparedMsg = self.prepareMessage(msg) for c in self.clients: c.sendPreparedMessage(preparedMsg) print("prepared message sent to {}".format(c.peer)) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False ServerFactory = BroadcastServerFactory #ServerFactory = BroadcastPreparedServerFactory factory = ServerFactory("ws://0.0.0.0:9000", debug = debug, debugCodePaths = debug) factory.protocol = BroadcastServerProtocol factory.setProtocolOptions(allowHixie76 = True) listenWS(factory) webdir = File(".") web = Site(webdir) reactor.listenTCP(8080, web) reactor.run() (mysite)[root@broadcast broadcast]#
客户端html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <script type="text/javascript"> String.prototype.startWith=function(s){ if(s==null||s==""||this.length==0||s.length>this.length) return false; if(this.substr(0,s.length)==s) return true; else return false; return true; } Date.prototype.format = function(format) { var o = { "M+" : this.getMonth() + 1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter "S" : this.getMilliseconds() } if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "") .substr(4 - RegExp.$1.length)); for ( var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; } var ws = null; function log(text) { /* document.getElementById("log").innerHTML = (new Date).getTime() + ": " + text + "<br>" + document.getElementById("log").innerHTML; */ document.getElementById("log").innerHTML = new Date().format('yyyy-MM-dd hh:mm:ss') + "," + text + "<br>" + document.getElementById("log").innerHTML; } function enterSend(){ if(event.keyCode == 13){ document.getElementById("sendbtn").click(); } } function startServer() { var url = document.getElementById("serverip").value;// "ws://192.168.0.102:8887"; if ('WebSocket' in window) { ws = new WebSocket(url); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(url); } else { log('浏览器不支持'); return; } ws.onopen = function() { log('唷嘻,连上了'); }; // 收到服务器发送的文本消息, event.data表示文本内容 ws.onmessage = function(event) { var thisdata = event.data; if(thisdata.startWith("open")){ //alert(thisdata); document.getElementById("username").value=thisdata.split(" ")[1]; }else{ //log(event.data); var showData=event.data.split(","); log(showData[0]+"说:"+showData[2]); } }; ws.onclose = function() { log('Closed! 刷新页面尝试连接.'); } } function sendMessage() { var textMessage = document.getElementById("textMessage").value; var username = document.getElementById("username").value; var toUser = document.getElementById("toUser").value;; if (ws != null && textMessage != "") { ws.send(username+","+toUser+","+textMessage); } document.getElementById("textMessage").value=""; } function stopconn() { ws.close(); } </script> <body onload="startServer()"> <input id="serverip" type="text" size="20" value="ws://182.254.155.153:9000" /> </br> 您的Id:<input id="username" type="text" readonly/></br> to Id:<input id="toUser" type="text" /> 如果为空则群发</br> <input id="textMessage" type="text" size="20" onkeydown="enterSend()" style="border:1;width:400px" /> <input id="sendbtn" type="button" onclick="sendMessage()" value="Send"> <div id="log"></div> </body> </html>