websocket

https://blog.csdn.net/qq_36688143/article/details/82226689

WebSocket:创建实例、发送和接收数据

1、Web Sockets:能够在客户端和服务端之间发送非常少量的数据,而不必担心HTTP那样字节级的开销
由于传递的数据包很小,因此WebSockets非常适合移动应用。
缺点:制定协议的时间比制定JavaScript API的时间还要长。


    1) URL模式:
    未加密:ws://    已加密:wss://
    2)创建WebSocket:先实例一个WebSocket对象并传入要连接的URL
    var socket = new WebSocket("ws://www.example.com/server.php);
    socket.close();    // 关闭连接


    3) 表示当前状态的readyState属性
    WebSocket.OPENING (0):正在建立连接
    WebSocket.OPEN (1):已经建立连接
    WebSocket.CLOSING (2):正在关闭连接
    WebSocket.CLOSE (3):已经关闭连接


     4)发送数据
    var message = { 
         time: new Date(), 
         text: "Hello world!", 
         clientId: "asdfp8734rew" 
    };
    socket.send(JSON.stringify(message));    // 复杂的数据结构要先进行序列化
      5)接收数据
    socket.onmessage = function(event){
        var data = event.data;    // data就是要解析的接收到的JSON字符串
    }

接收JSON消息

https://geek-docs.com/websocket/websocket-tutorials/websockets-send-receive-messages.html

socket.onmessage = function(event) {

      //create a JSON object
      var jsonObject = JSON.parse(event.data);
      var username = jsonObject.name;
      var message = jsonObject.message;

      console.log(Received data string);
 
}

  


      6)其他事件:在连接生命周期的不同阶段触发
    open:在成功建立连接时触发
    error:在发生错误时触发

https://www.cnblogs.com/JinMuBaoBao/articles/10268956.html

flask实现websocket

https://www.cnblogs.com/JinMuBaoBao/articles/10268956.html

JSON 字符串转换为 JavaScript 对象

https://www.runoob.com/js/js-json.html

var text = '{ "sites" : [' +
    '{ "name":"Runoob" , "url":"www.runoob.com" },' +
    '{ "name":"Google" , "url":"www.google.com" },' +
    '{ "name":"Taobao" , "url":"www.taobao.com" } ]}';
    
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.sites[1].name + " " + obj.sites[1].url;

  

原文地址:https://www.cnblogs.com/kekeoutlook/p/12327446.html