2013-06-13 50 views
0
#!C:/Python27/python.exe -u 
import tornado 
import tornado.websocket 
import tornado.wsgi 
import tornado.web 
import tornado.httpserver 
import tornado.tcpserver 
import json 

from py2neo import neo4j, cypher 
graph_db = neo4j.GraphDatabaseService() 
class request(tornado.web.RequestHandler): 
    def sr(): 
     self.set_header('Content-type','application/json') 
class ChatWebSocket(tornado.websocket.WebSocketHandler): 
    clients = [] 
    def open(self): 
     ChatWebSocket.clients.append(self) 
    def on_message(self, message): 
     query = "START a=node:node_auto_index(uid='twitter') CREATE a-[:ch]-(t{con:'"+message+"'}) RETURN a" 
    data, metadata = cypher.execute(graph_db, query) 
     for client in ChatWebSocket.clients: 
     print(client) 
     t=json.loads(message) 
     client.write_message('Content-type:application/json\n') 
     client.write_message(json.dumps({'a':t['b']})) 
     print(t['b']) 
    def on_close(self): 
     ChatWebSocket.clients.remove(self) 
    tornado_app = tornado.web.Application([ 
    (r'/websocket', ChatWebSocket), 
    (r'.*', tornado.web.FallbackHandler) 
    ]) 
tornado_app.listen(5094) 
tornado.ioloop.IOLoop.instance().start() 

這裏是我的代碼示例我接受json的消息獲取其實例b 並將json再次發送到客戶端。但客戶端將標題視爲普通字符串。如何通過python龍捲風在websocket發送json頭?

回答

0

Websockets不需要標題。只需將你的json作爲字符串發送。

+0

那麼我如何在客戶端訪問這些字符串作爲json? – user2481309

+1

好吧,我得到了answer.send它像一個字符串annd他們轉換爲使用JSON.parse()的對象,並且它it.its一個JavaScript接受json現在 – user2481309