WebSocket bidirectional communication
WebSockets
Is a new protocol borrowed from the handshake specification for compatibility with existing browsersHTTP
The agreement to complete the partial handshake (withHTTP
The agreement is basically irrelevant).
The advantages of the WebSocket
1.
WebSocket
Both client and server can actively send data to each other.HTTP
In 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