WebSocket instance, trigger event and method

WebSocket trigger event

The following are related events of the WebSocket object. Suppose we used the above code to create a Socket object:

event Event handler description
open Socket.onopen Triggered when the connection is established
message Socket.onmessage Triggered when the client receives server data
error Socket.onerror Triggered when a communication error occurs
close Socket.onclose Triggered when the connection is closed

WebSocket method

The following are the relevant methods of the WebSocket object. Suppose we used the above code to create a Socket object:

method description
Socket.send()

Use connection to send data

Socket.close()

Close the connection

WebSocket connection example

Most browsers currently support the WebSocket() interface. You can try examples in the following browsers: Chrome, Mozilla, Opera and Safari.

<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>WebSocket实例</title>
      <script type="text/javascript">
         function WebSocketTest()
         {
            if ("WebSocket" in window)
            {
               alert("您的浏览器支持 WebSocket!");
               var ws = new WebSocket("ws://localhost:9998/echo");    // 打开一个 web socket
               ws.onopen = function()
               {
                  ws.send("发送数据");    // Web Socket 已连接上,使用 send() 方法发送数据
                  alert("数据发送中...");
               };
                
               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  alert("数据已接收...");
               };
                
               ws.onclose = function()
               { 
                  alert("连接已关闭...");     // 关闭 websocket
               };

            }else{
               alert("您的浏览器不支持 WebSocket!");     // 浏览器不支持 WebSocket
            }
         }
      </script>
   </head>
   <body>
      <div id="sse">
         <a href="javascript:WebSocketTest()">运行 WebSocket</a>
      </div>
      
   </body>
</html>

 

Guess you like

Origin blog.csdn.net/weixin_43452467/article/details/113257048