-
StackOverflow 文档
-
JavaScript 教程
-
WebSockets
-
使用字符串消息
var wsHost = "ws://my-sites-url.com/path/to/echo-web-socket-handler";
var ws = new WebSocket(wsHost);
var value = "an example message";
//onmessage : Event Listener - Triggered when we receive message form server
ws.onmessage = function(message) {
if (message === value) {
console.log("The echo host sent the correct message.");
} else {
console.log("Expected: " + value);
console.log("Received: " + message);
}
};
//onopen : Event Listener - event is triggered when websockets readyState changes to open which means now we are ready to send and receives messages from server
ws.onopen = function() {
//send is used to send the message to server
ws.send(value);
};