码迷,mamicode.com
首页 > Web开发 > 详细

tornado websocket

时间:2017-05-14 21:53:22      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:handler   浏览器   for   handle   条件   doc   nod   tpc   dem   

近期在网上找了些websocket的资料看了下。node和tornado等等本身已经实现了websocket的封装,所以使用起来会比較简单,php假设想要写websocket还须要自己跑一整套流程,比較麻烦。

依据网上的资料写了一个简单的websocket的demo,果真炫酷掉渣天,我是用tornado,网上多是实现实时聊天室的样例,想要实现点对点的聊天功能还须要在send函数那里加条件,目測是依据浏览器用户的id去推断的。代码例如以下:

服务端代码:

#!/usr/bin/python
#coding:utf-8
import os.path

import tornado.httpserver
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpclient
import tornado.websocket

import json
class IndexHandler(tornado.web.RequestHandler):
	def get(self):
		self.render("index.html")

class SocketHandler(tornado.websocket.WebSocketHandler):
	"""docstring for SocketHandler"""
	clients = set()

	@staticmethod
	def send_to_all(message):
	    for c in SocketHandler.clients:
	        c.write_message(json.dumps(message))

	def open(self):
	    self.write_message(json.dumps({
	        ‘type‘: ‘sys‘,
	        ‘message‘: ‘Welcome to WebSocket‘,
	    }))
	    SocketHandler.send_to_all({
	        ‘type‘: ‘sys‘,
	        ‘message‘: str(id(self)) + ‘ has joined‘,
	    })
	    SocketHandler.clients.add(self)

	def on_close(self):
	    SocketHandler.clients.remove(self)
	    SocketHandler.send_to_all({
	        ‘type‘: ‘sys‘,
	        ‘message‘: str(id(self)) + ‘ has left‘,
	    })

	def on_message(self, message):
		SocketHandler.send_to_all({
            ‘type‘: ‘user‘,
            ‘id‘: id(self),
            ‘message‘: message,
        })
		
##MAIN
if __name__ == ‘__main__‘:
	app = tornado.web.Application(
		handlers=[
			(r"/", IndexHandler),
			(r"/chat", SocketHandler)
		],
		debug = True,
		template_path = os.path.join(os.path.dirname(__file__), "templates"),
        static_path = os.path.join(os.path.dirname(__file__), "static")
	)
	app.listen(8000)
	tornado.ioloop.IOLoop.instance().start()

client代码:

<html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8000/chat");
ws.onmessage = function(event) {
	console.log(event);
}
function send() {
	ws.send(document.getElementById(‘chat‘).value );
}
</script>
</head>

<body>
	<div>
		hello
		<input id="chat">
		<button  onclick="send()">send</button>
	</div>	
</body>
</html>


tornado websocket

标签:handler   浏览器   for   handle   条件   doc   nod   tpc   dem   

原文地址:http://www.cnblogs.com/wzzkaifa/p/6853700.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!