跳转至

WebSocket


概述

演示WebSocket,WebSocket连接时是用HTTP协议,登录后会转成简单的WebSocket协议。


代码


var server = "xxx.xxx.xxx.xxx";
var port = 1000;

var isConnected = false;
function packet(data)   //WebSocket组包
{
    var len = data.length + 2;
    if(data.length > 125) len += 2;
    var b = Bytes.create(len);
    b[0] = 0x81;
    if(data.length < 126)
    {
        b[1] = data.length;
        b.sets(data, 2);
    }
    else
    {
        b[1] = 126;
        b.seti(data.length, 2, "2b");
        b.sets(data, 4);
    }
    return b;
}

function parse(data)    //WebSocket解包
{
    var s;
    var len = data[1];
    if(len < 126)
    {
        s = data.gets(2);
    }
    else
    {
        len = data.geti(2, "2b");
        s = data.gets(4);
    }
    print("recv:", s);
}

function httpCB(data)   //HTTP协议
{
    print(JSON.stringify(data));
    if(data.code == 101)    //服务器返回Code:101说明已切换在WebSocket
    {
        print("connect success");
        isConnected = true;
        Net.send(0, packet("test"));
    }
}
var http = Packet.HTTP.Parser.create(httpCB);

function connect()  //发送连接包
{
    var str = "GET / HTTP/1.1\r\n";
    str += "Upgrade: websocket\r\n";
    str += "Connection: Upgrade\r\n";
    str += "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n";
    str += "\r\n";
    Net.send(0, str);
}
function netCB(m)
{
    switch(m.event)
    {
        case Net.READY:
            isConnected = false;
            Net.tcp(0, server, port);
            break;
        case Net.CONN_OK:
            connect();
            break;
        case Net.CONN_FAIL:
            print("connect failed");
            break;
        case Net.CONN_CLOSE:
            print("connect closed");
            break;
        case Net.RECV:
            if(isConnected)
            {
                parse(m.data);
            }
            else
            {
                http.parse(m.data);
            }
            break;
    }
}

GPIO.set(GPIO.POWER, 1);
Net.init();
while(true)
{
    var m = Event.get();
    switch(m.msg)
    {
        case Event.NET_EVENT:
            netCB(m);
            break;
    }
}


下载代码(右键另存为):ws.js