Skip to content

Instantly share code, notes, and snippets.

@luchenqun
Created December 26, 2017 02:19
Show Gist options
  • Save luchenqun/279793690b43608b53f0135f7d70d96f to your computer and use it in GitHub Desktop.
Save luchenqun/279793690b43608b53f0135f7d70d96f to your computer and use it in GitHub Desktop.
// 创建 WebSocket 对象
var ws = new WebSocket('wss://localhost:3000/');
// 连接建立时触发
ws.onopen = function() {
console.log('WebSocket已连接');
// 使用连接发送数据
ws.send('Hello!');
};
// 客户端接收服务端数据时触发
ws.onmessage = function(msg) {
console.log(msg); // MessageEvent {isTrusted: true, data: "ECHO: Hello!" ...}
// 关闭连接
ws.close();
};
// 通信发生错误时触发
ws.onerror = function(e) {
console.log(e);
};
// 连接关闭时触发
ws.onclose = function() {
console.log('WebSocket已关闭');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment