websocket发送消息问题

时间:2014-09-27 12:11:28

标签: javascript websocket

下面的代码连接到一个Web socked服务器,一旦调用函数lighton(),它就会向服务器发送一个Web套接字消息,但是由于某种原因这不起作用,任何帮助

var cam_on;
var sock = null;
function connect()
{
    var url = "ws://" + location.host + ":8888/ws";
    var ws = new WebSocket(url);
    ws.onopen = function() 
    {

        $('#lighton').button("enable");
        $('#lightoff').button("enable");
        $('#stop').button("enable");

    };

    ws.onmessage = function (evt) 
    {
       alert(evt.data);
    };

    ws.onclose = function(evt) 
    { 
        alert("Connection close"); 
         $('#lighton').button("disable");
        $('#lightoff').button("disable");
        $('#stop').button("disable");

    };

};

function ws_send(message)
{

    if(ws)
        {
            ws.send(message);
       }    
};

function lighton() {
        alert("button pressed");
        ws_send("IR on");

};

更新:已解决,但如果可能,则上述内容更清晰

function init() {


//   connect();

   var url = "ws://" + location.host + ":8888/ws";
    var ws = new WebSocket(url);
    ws.onopen = function() 
    {

        $('#lighton').button("enable");
        $('#lightoff').button("enable");
        $('#stop').button("enable");

    };

    ws.onmessage = function (evt) 
    {
       alert(evt.data);
    };

    ws.onclose = function(evt) 
    { 
        alert("Connection close"); 
         $('#lighton').button("disable");
        $('#lightoff').button("disable");
        $('#stop').button("disable");

    };

    var lighton = document.getElementById("lighton");
    var lightoff = document.getElementById("lightoff");

    lighton.addEventListener("click", function(event)
    {
        ws.send("IR on");

    });

    lightoff.addEventListener("click", function(event)
    {
        ws.send("IR off");

    });


}

0 个答案:

没有答案