#!/usr/bin/python27
import tornado
import tornado.websocket
import tornado.wsgi
import motor
import json
import jsonpickle
from tornado.ioloop import IOLoop
class MainHandler(tornado.web.RequestHandler):
def get(self):
db = self.settings['db']
class ChatWebSocket(tornado.websocket.WebSocketHandler):
clients = []
ids={}
def my_callback(result, error):
print 'result', repr(result)
IOLoop.instance().stop()
def open(self):
ChatWebSocket.clients.append(self)
self.write_message(jsonpickle.encode(self))
def on_message(self, message):
def get_current_user(self):
print(self)
to=db.today.ensure_index()
array=message
data=json.loads(array)
if data['st']=='ty':
for client in ChatWebSocket.clients:
client.write_message('"me":"ty","con":'+data['whom']+' is typing')
elif (data['st']=='me'):
print("ok")
ChatWebSocket.ids[''+data['who']+'']=data['ob']
for s in ChatWebSocket.ids:
print(s)
else:
doc={'who':data['who'],'whom':data['whom'],'mes':data['mes']}
to.insert(doc,callback=my_callback)
for client in ChatWebSocket.clients:
client.write_message('"me":"ty","con":"'+data[mes]+'"')
def on_close(self):
ChatWebSocket.clients.remove(self)
db=motor.MotorClient().open_sync().chat
tornado_app = tornado.web.Application([(r'/websocket', ChatWebSocket),
(r'.*', tornado.web.FallbackHandler), (r'/', MainHandler)],db=db)
tornado_app.listen(5069)
tornado.ioloop.IOLoop.instance().start()
我正在尝试将on_open函数上的websocket对象发送到客户端 它将id与对象一起返回, 但它说错误:TypeError:'MotorCollection'对象在json.encode中不可调用(self) 请帮忙