日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

autobahn的helloworld

發布時間:2023/12/29 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 autobahn的helloworld 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python2.7.8可用,python2.6一樣的代碼就有問題

https://github.com/tavendo/AutobahnPython/

git clone https://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
http://wangxiaoxu.iteye.com/blog/1896624

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


廣播的例子修改如下
[code="java"]
(mysite)# 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)#
[/code]
客戶端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>

總結

以上是生活随笔為你收集整理的autobahn的helloworld的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。