`
haoningabc
  • 浏览: 1477761 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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


广播的例子修改如下
(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>

分享到:
评论

相关推荐

    Autobahn

    Autobahn

    autobahn.jar

    标题中的"autobahn.jar"是一个Java库,用于实现WebSocket协议和WAMP(Web Application Messaging Protocol)协议。这个库由crossbario公司在GitHub上维护,是Autobahn|Python的一个Java版本,它允许开发者在Java应用...

    autobahn-0.5.0.jar 以及使用的代码

    client.publish("mytopic", "Hello, WebSocket!"); } } ``` 在上述代码中,`use.txt`可能包含了如何在实际项目中使用`autobahn-0.5.0.jar`的示例代码或说明。文件内容可能包括如何配置WebSocket服务器,如何处理...

    autobahn-0.5.0包特意分享下

    Autobahn库源自C++的Autobahn WebSocket库,它是一个开源项目,致力于提供高效、可靠的WebSocket客户端和服务器实现。版本0.5.0是该库的一个特定版本,可能包含了一些特定的优化或特性。 在Android开发中,使用...

    Python库 | autobahn-17.6.2.tar.gz

    《Python库Autobahn详解——基于17.6.2版本》 在Python的世界里,丰富的库资源是其强大功能的重要支撑。今天我们要探讨的是一个名为Autobahn的Python库,它在17.6.2版本中的特性与应用。Autobahn是一个用于构建...

    autobahn-0.5.0

    尽管这个包的名字是"autobahn-0.5.0",但在Android环境中,我们通常会找到针对Android优化的版本,比如一个包含Java代码的JAR文件,即"autobahn-0.5.0.jar"。 在Android应用中,"autobahn-0.5.0.jar"可能包含了...

    Python库 | autobahn-19.8.1-py2.py3-none-any.whl

    **Python库 autobahn-19.8.1-py2.py3-none-any.whl** `autobahn` 是一个强大的Python库,专为WebSockets和异步网络应用设计。这个压缩包文件“autobahn-19.8.1-py2.py3-none-any.whl”是该库的一个特定版本,支持...

    autobahn-0.5.0.jar

    这是autobahn-0.5.0.jar的关于websocket的jar包

    autobahn-python, 在 python 中为 Twisted 和 asyncio,web socket和,.zip

    autobahn-python, 在 python 中为 Twisted 和 asyncio,web socket和, Autobahn|Pythonweb socket & WAMP用于 Twisted 和asyncio上的python 。 快速链接: 源代码 - 文档- web socket示例- web WebSocke

    PyPI 官网下载 | autobahn-19.9.3-py2.py3-none-any.whl

    **PyPI 官网下载 | autobahn-19.9.3-py2.py3-none-any.whl** PyPI(Python Package Index)是Python开发者最常用的一个资源库,它提供了大量的Python软件包供用户下载和使用。在本案例中,我们讨论的是一个名为...

    autobahn-0.11.2.jar

    WebSocket网络请求需要用到的jar包。

    Android-autobahn-java.zip

    Android-autobahn-java.zip,Android和Java 8中的WebStuts&WAMP,安卓系统是谷歌在2008年设计和制造的。操作系统主要写在爪哇,C和C 的核心组件。它是在linux内核之上构建的,具有安全性优势。

    Python库 | autobahn-22.2.2.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:autobahn-22.2.2.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    autobahn-js, 在浏览器和NodeJS的JavaScript中,WAMP.zip

    autobahn-js, 在浏览器和NodeJS的JavaScript中,WAMP 收费的高速公路 |JSWAMP用于浏览器和 NodeJS 。 收费收费是高速公路项目的子项目,它提供了在许可协议的 Web应用程序消息传递协议V2的开源实施。WAMP提供异步...

    autobahn-api:Autobahn GmbH 数据的 API

    查询单一高速公路上的数据(例如 A1) 建筑工地 (详情: : ) 网络摄像头: : (详细信息: : ) 停车位: : (详情: https : //verkehr.autobahn.de/o/autobahn/details/parking_lorry/[ID] ) 交通报告: ...

    PyPI 官网下载 | autobahn-20.1.3-py2.py3-none-any.whl

    资源来自pypi官网。 资源全名:autobahn-20.1.3-py2.py3-none-any.whl

    Autobahn(itunes下载加速器)

    **Autobahn(iTunes下载加速器)** Autobahn是一款专为提升iTunes下载速度设计的工具。在日常使用中,人们可能会发现iTunes在下载音乐、应用程序、电影或其他内容时速度较慢,特别是在网络环境不佳或者面对大文件时...

    PyPI 官网下载 | autobahn-0.9.4.zip

    **PyPI 官网下载 | autobahn-0.9.4.zip** `autobahn-0.9.4.zip` 是一个从Python的官方第三方库仓库PyPI(Python Package Index)下载的压缩包,其中包含了Python库`autobahn`的0.9.4版本。`autobahn`是一个用于实现...

    Autobahn-Java 是 Autobahn 项目的子项目,提供开源客户端实现 WebSocket 协议 Web 应用程序

    Autobahn|Java 是 Autobahn 项目的子项目,提供开源客户端实现 WebSocket 协议 Web 应用程序消息传递协议 (WAMP) 运行在 Android 和 Netty/Java8/JVM 上。 WebSocket 层使用基于回调的用户 API,并且是专门为 ...

Global site tag (gtag.js) - Google Analytics