HTML5--WebSocket API

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")


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值