2014-02-27 87 views
1

有沒有辦法發送websocket消息的參數?我想發送一條消息到網站,並從網站能夠重定向到正確的div。發送websocket消息給客戶端與參數

這個概念是發送消息+ ID,並根據ID重定向它所屬的地方。該ID可以是數字或字母。

到目前爲止,這是我的部分服務器代碼(簡化):

def on_message(self, message): 
    global c 
    if message == "w": 
    c = "8"; 
    if message == "s": 
    c = "2" 
    if c == '8' : 
    self.write_message("This should appear in first div ") 
    elif c == '2' : 
    self.write_message("This should appear in second div ") 

和客戶端代碼:

<div id="output">First div</div> 
<div id="output2">Second div</div> 

socket.onmessage = function(msg) 
{ 
    showServerResponse(msg.data); 
} 
function showServerResponse(txt) 
{ 
    var p = document.createElement('p'); 
    p.innerHTML = txt; 
    document.getElementById('output').appendChild(p); 
} 

這被綁定到發送的任何消息格 「輸出」。

我應該重寫write_message函數嗎?它應該是什麼樣子?

感謝您的任何建議。

回答

0

所以,我將它修復成JSON,但現在我是從網站發送信件:

socket.send("w") 
socket.send("s") 

和服務器端都在等待JSON對象:

forward = { "messageid": 1, 
     "message": "First message" 
     } 
backward = { "messageid": 2, 
     "message": "Second message" 
     } 

,並根據情況我發回給客戶端JSON:

def on_message(self, message): 
    global c 
    if message == "w": 
    c = "8"; 
    if message == "s": 
    c = "2" 
    if c == '8' : 
    self.write_message(json_encode(forward)) 
    elif c == '2' : 
    self.write_message(json_encode(backward)) 

返回瀏覽器是等待json對象的函數:

<div id="output">First div</div> 
<div id="output2">Second div</div> 

socket.onmessage = function(msg){ 
var message = JSON.parse(msg.data); 
if(message.messageid== 1) 
    { 
    showServerResponse(message.message) 
    } 
if(message.messageid== 2) 
    { 
    showServerResponse2(message.message) 
    } 
} 

,功能展現給DIV:

function showServerResponse(txt) 
{ 
var p = document.createElement('p'); 
p.innerHTML = txt; 
document.getElementById('output').appendChild(p); 
} 

第二個功能是showServerResponse2(txt)其發送到'output2'

這樣你可以發送消息從服務器到客戶端到不同的div,這取決於發送的參數,這是原始問題。建議使用正確的參數發送每條消息,否則可能會丟失。

2

如果您想發送參數,只需將您的消息作爲JSON字符串發送。這是通過websockets完成的方法。

在JavaScript中,你可以發送類似

socket.send(JSON.stringify({messageid : "your id", message : "your text message"}); 

和接收JSON字符串像

socket.onmessage = function(data){ 
    var message = JSON.parse(data.data); 
    // now you have your JSON object in the var message 

    console.log(message); // outputs the object in the browser's console 
} 

其實我覺得一個好的做法是隻使用JSON(或XML)進行通信當使用websocket。這樣你的應用程序將更加連貫。

使用JSON還允許您將結構化消息發送到客戶端。您的服務器端語言肯定有一個JSON庫。

對不起,我不能幫助更多的服務器端腳本,因爲我不知道龍捲風,幾乎沒有蟒蛇,但tornado write a Jsonp object應該幫助。

+0

好主意,我現在正在看它。所以..我應該能夠使用JSON.parse訪問服務器端的參數,對吧? 我可以以同樣的方式將JSON數據發送到服務器嗎? – Zoidbergus

+0

在服務器上,你將不得不使用你的python JSON庫提供的函數解析JSON,這個函數就像'from tornado.escape import json_decode',然後你可以使用'json_decode(data_received)'。做一些研究,找出確切的方法來做到這一點,我現在只是猜測。 – Johnride

+0

解決了,感謝您的指導,我會寫我的解決方案作爲答案。 – Zoidbergus

相關問題