1.浏览器检测websocket兼容性
if(window.WebSocket){
console.log('支持')
}else{
console.log('去死')
}
2.websocket的对象创建与通信端口连接
var url = 'ws://localhost:8080/test';
//ws://前缀表示websocket连接,wss://表示安全的websocket连接
var socket = new WebSocket(url);
3.websocket对象事件(监听,发送,关闭)
websocket编程遵循异步编程模型,打开socket不需要主动向服务器发送请求,只需要等待事件发生后调用它的回调函数
//使用open事件双方握手
socket.open = function (){
console.log('open');
socket.send('hello server'); //使用send事件发送消息
}
//使用onmessage事件监听server端的响应信息
socket.onmessage = function (e){
console.log(e.data);
}
//使用onclose关闭此通讯
socket.onclose = function (){
console.log('this socket is closed');
}
在socket打开状态中,可以使用send函数推送数据到server
socket.send("hello server i'm conming again")