2016-12-10 30 views
0

我想通過一個JSON對象和WebSocket連接,以推動一些信息給客戶端閱讀JSON發送。 JSON對象被正確發送,因爲我使用JSON Web應用程序進行了檢查,並且沒有問題。使用的WebSocket與jQuery

一旦recevied,這是jquery的客戶端的代碼;

$(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對象?發佈完整的代碼。 – TigOldBitties

+0

好吧,我有張貼在這兩個服務器端和客戶端的整個代碼。 – gcp900

+0

是否正在觸發onmessage事件?你可以在事件中放置一個console.log('trigger')並查看它是否被觸發? – TigOldBitties

回答

0

原來沒有什麼不對的實施,只是在迴應如何寫在HTML

$("#dia").text(json.tiempo)