14.6 socket跨域
原理:客户端通过onopen的send发送数据,服务端通过message监听发送来的数据
socket.html
<script> // 高级api 不兼容 socket.io // http单向的,socket是双向的,传输都靠tcp let socket = new WebSocket('ws://localhost:3000') socket.onopen = () => { // 多个页面通信就是 先发给服务器,服务器再发给另一个页面 socket.send('我爱你') } socket.onmessage = e => { console.log(e.data) } </script>
server.js
let express = require('express') let app = express() let WebSocket = require('ws') let wss = new WebSocket.Server({port:3000 }) wss.on('connection', ws => { ws.on('message', data => { console.log(data) ws.send('我不爱你') }) })