WebSocket bidirectional communication

WebSocketsIs a new protocol borrowed from the handshake specification for compatibility with existing browsersHTTPThe agreement to complete the partial handshake (withHTTPThe agreement is basically irrelevant).
The advantages of the WebSocket
1. WebSocketBoth client and server can actively send data to each other.HTTPIn the protocol, the server cannot initiate contact with the client

2. Create and destroy TCP requests at different frequencies to reduce bandwidth usage and save server resources.
WebSocket method
1.Socket.send() : send(data)Method uses a link to transfer data

2.Socket.close(): close()Method is used to terminate any existing links
WebSocket API
The event Event handler describe
open Socket.onopen Trigger this event when establishing a socket link
message Socket.onmessage Triggered when the client receives data from the server
error Socket.onerror Triggered when a link error occurs
close Socket.onclose Triggered when the link is closed
Var Socket = new WebSocket('ws://echo.websocket.org');
Socket.onopen = function(e){
    Socket.send('hello');
}
Socket.onmessage = function(e){
    console.log('message') console.log(e.data); Socket.close(); // terminate the link // socket.send ('kiwi'); } socket. onclose =function(e){
    console.log('close');
}
Socket.onerror = function(){
    console.log('error')
}
//message
//hello
//close
Copy the code