websocket客户端

websocket_test.html,使用浏览器打开html文件,即可在console中看到三次websocket连接的结果

<!DOCTYPE HTML>

<html>
   <head>
      <script type = "text/javascript">
         function WebSocketTest() {
            if ("WebSocket" in window) {
               console.log("WebSocket is supported by your Browser!");

               // Let us open a web socket
               var ws = new WebSocket("ws://ime-handwriting-adapter.com.cn/ws/ime_handwriting_recognition?SN=77777777");

               ws.onopen = function() {

                  // Web Socket is connected, send data using send()
                  var message = {
                        "data": "614, 732, 604, 753, 574, 807, 549, 875, 554, 942, 588, 964, 621, 984, 657, 992, 689, 987, 710, 977, 711, 977, -1, 0, -1, -1, 619, 949, 604, 966, 584, 989, 563, 1007, 540, 1014, 522, 1014, 512, 1007, 516, 989, 529, 963, 557, 919, 597, 875, 644, 823, 682, 785, 700, 768, 703, 766, 698, 775, 687, 796, 679, 824, 679, 854, 692, 877, 720, 891, 756, 906, 783, 917, 796, 928, 792, 951, 783, 973, 764, 997, 726, 1010, 696, 1013, 683, 1008, 683, 990, 695, 960, 722, 916, 754, 878, 787, 851, 814, 830, 837, 816, 837, 816, -1, 0, -1, -1",
                        "mode": "0",
                        "id": 1
                  }
                  var str_message = JSON.stringify(message)
                  ws.send(str_message);
                  console.log("Message is sent...");
               };

               ws.onmessage = function (evt) {
                  var received_msg = evt.data;
                  console.log("Message is received: ", evt.data);
               };

               ws.onclose = function() {
                  console.log("Connection is closed...");
               };
            } else {
               console.log("WebSocket NOT supported by your Browser!");
            }
         }

         // 循环发送三次websocket请求
         for (let i=0; i<3; i++) {
            setTimeout(function(){WebSocketTest()}, 5000*i )
         }

      </script>
   </head>
   
   <body>
      <div id = "sse">
         <a>WebSocket Test</a>
      </div>
      
   </body>
</html>
posted @ 2021-07-03 15:17  Sincere_Ye  阅读(313)  评论(0编辑  收藏  举报