HTML5--WebSocket API

来源:互联网 发布:sketchbook mac 破解 编辑:程序博客网 时间:2024/06/05 19:32

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函数推送数据到serversocket.send("hello server i'm conming again")


原创粉丝点击