2016-12-10 6 views
0

JSONオブジェクトとwebsocket接続を介してクライアントに情報をプッシュしようとしています。 JSONオブジェクトはJSON Webアプリケーションでチェックして正常に送信されたため正しく送信されます。JSONをJQueryでwebsocketを使用して読み取る

これが受信されると、これはjquery-clientコードです。

$(document).ready(function(){ 

    var WEBSOCKET_ROUTE = "/ws"; 

    if(window.location.protocol == "http:"){ 
     //localhost 
     var ws = new WebSocket("ws://" + window.location.host + WEBSOCKET_ROUTE); 
     } 
    else if(window.location.protocol == "https:"){ 
     //Dataplicity 
     var ws = new WebSocket("wss://" + window.location.host + WEBSOCKET_ROUTE); 
     } 

    ws.onopen = function(evt) { 
     $("#ws-status").html("Connected"); 
     }; 

    ws.onmessage = function(evt) { 
    var json = JSON.parse(evt.data); 
    $("#dia").html(json); 
     }; 

    ws.onclose = function(evt) { 
     $("#ws-status").html("Disconnected"); 
     }; 

$("#manual_on").click(function(x){ 
      var msg = { 
    type: 'manual', 
     text: $('#manual_on').val(), 
    }; 
    ws.send(JSON.stringify(msg)); 
    $('#manual_on').val()= ""; 
     }); 

$("#manual_off").click(function(x){ 
     var msg = { 
    type: 'manual', 
     text: $('#manual_off').val(), 
    }; 
    ws.send(JSON.stringify(msg)); 
    $('#manual_off').val() = ""; 
     }); 

$("#apertura").click(function(x){ 
     var msg = { 
    type: 'programacion', 
     hora: $('#hora').val(), 
    minutos: $('#minutos').val(), 
    tiempo: $('#tiempo').val(), 
    lunes: $('#lu').prop('checked'), 
    martes: $('#ma').prop('checked'), 
    miercoles: $('#mi').prop('checked'), 
    jueves: $('#ju').prop('checked'), 
    viernes:$('#vi').prop('checked'), 
    sabado: $('#sa').prop('checked'), 
    domingo: $('#do').prop('checked'), 
    }; 
    ws.send(JSON.stringify(msg)); 
     }); 
    }); 

また、これは、サーバー側のpython /竜巻コードです:

#! /usr/bin/python 

import tornado.httpserver 
import tornado.websocket 
import tornado.ioloop 
import tornado.web 
from tornado.ioloop import PeriodicCallback 
import socket 
import os.path 
import json 
import time 

#Tornado Folder Paths 
settings = dict(
    template_path = os.path.join(os.path.dirname(__file__), "templates"), 
    static_path = os.path.join(os.path.dirname(__file__), "static") 
    ) 


class MainHandler(tornado.web.RequestHandler): 
    def get(self): 
    print "[HTTP](MainHandler) User Connected." 
    self.render("index.html") 

class WSHandler(tornado.websocket.WebSocketHandler): 
    def open(self): 
    self.callback = PeriodicCallback(self.send_msg, 120) 
     self.callback.start() 
     print 'new connection' 

    def on_message(self, message):  
    data = json.loads(message) 

    if data['type'] == 'programacion': 

     hora=int(data['hora']) 
     minuto=int(data['minutos']) 
     tiempo=int(data['tiempo']) 
     l=int(data['lunes']) 
     m=int(data['martes']) 
     x=int(data['miercoles']) 
     j=int(data['jueves']) 
     v=int(data['viernes']) 
     s=int(data['sabado']) 
     d=int(data['domingo']) 
     global daylist 
      daylist = [] 
      n=-1 
      for i in (l, m, x, j, v, s, d): 
      n=n+1 
      if i==1: 
        daylist.append(n) 
     print(time.time()) 

    elif data['type'] == 'manual': 
      print('manual') 



    def on_close(self): 
     print 'connection closed' 

    def send_msg(self): 
     timing=time.strftime("%H:%M:%S") 
     timing2={'tiempo':timing} 
     print json.dumps(timing2) 
     self.write_message(json.dumps(timing2)) 

#sched.add_cron_job(job_function, month='6-8,11-12', day='3rd fri', hour='0-3') 


application = tornado.web.Application([ 
    (r'/', MainHandler), 
    (r'/ws', WSHandler), 
    ], **settings) 



if __name__ == "__main__": 

    http_server = tornado.httpserver.HTTPServer(application) 
    http_server.listen(8888) 
    myIP = socket.gethostbyname(socket.gethostname()) 
    print '*** Websocket Server Started at %s***' % myIP 
    tornado.ioloop.IOLoop.instance().start() 

すべてが、私はクライアント側でJSONを読み、HTMLでそれを置くしようとしたときを除き、よく働きます。私はこのフォーラムとインターネットで探していますが、何も見つかりませんでした。あなたは私に手を差し伸べることができますか?

ありがとうございました。

+0

はどのようにあなたのWSがオブジェクトのインスタンス化されているHTMLで記述された方法に、実装と間違って何もありませんでしたが判明しますか?完全なコードを投稿してください。 – TigOldBitties

+0

私はサーバーとクライアント側の両方でコード全体を投稿しました。 – gcp900

+0

はonmessageイベントがまったくトリガーされていますか?イベントの中にconsole.log( 'trigger')を入れて、それがまったくトリガされているかどうか確認できますか? – TigOldBitties

答えて

0

はちょうど応答が

$("#dia").text(json.tiempo) 
関連する問題