赞
踩
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
var ws = new WebSocket('ws:××××××') //必须是以ws或wss开头
- var ws = new WebSocket('ws:××××××')
- ws.onopen = function(){
- alert("连接成功")
- }
onerror:连接不成功时触发
- var ws = new WebSocket('ws:××××××')
- ws.onerror = function(){
- alert('连接失败')
- };
onmessage:接收消息时触发
- var ws = new WebSocket('ws:××××××')
- ws.onmessage = function(msg){
- console.log(msg);
- var data = JSON.parse(msg.data)
- console.log(data);
- };
send:发送数据
- <body>
- <button onclick="send()">发送消息</button>
- </body>
-
-
- <script>
- var ws = new WebSocket('ws:××××××')
- function send(){
- console.log(1);
- var message = {
- from:'Jon',
- to:'TOM',
- text:'晚上好'
- };
- ws.send(JSON.stringify(message));
- }
- </script>
点击发送按钮,触发send事件,可发送消息,对应的用户可接收到数据
代码总结
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <button onclick="send()">发送消息</button>
- </body>
- <script>
-
- //连接服务器
- var ws = new WebSocket('ws:××××××')
- //连接成功触发
- ws.onopen = function(){
- alert("连接成功")
- };
- //连接不成功触发
- ws.onerror = function(){
- alert('连接失败')
- };
- //接收消息触发
- ws.onmessage = function(msg){
- console.log(msg);
- var data = JSON.parse(msg.data)
- console.log(data);
- };
- function send(){
- console.log(1);
- var message = {
- from:'Jon',
- to:'TOM',
- text:'晚上好'
- };
-
- ws.send(JSON.stringify(message));
-
- }
-
- </script>
- </html>
更多详情可查看 :菜鸟教程https://www.runoob.com/html/html5-websocket.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。