socket 客户端与服务端链接
客户端:
// index.html引入
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.0/socket.io.dev.js"></script>
//链接node层
initSocket() {
var websocket;
let that=this;
var websocket=null;
let sock = io.connect(wsUrl) // 这里是 ws 协议,不是 http 协议
sock.on('connect',()=>{
console.log('connected')
})
//建立链接事件
sock.on('clientFun', data =>{
var obj=data?JSON.parse(data):''
// console.log(obj,"node数据")
})
//监听服务端请求->客户端
sock.on('disconnect',()=>{
console.log('closed')
})
},
node层服务端
express启server
let server = http.createServer((req, res)=>{})
server.listen(8000)
const io = require('socket.io')//和客户端浏览器进行链接
let wsServer = io.listen(server);
wsServer.on('connection', sock=>{
// logger("浏览器重新连接")
console.log("web connection nodeServer ", sock.id)
//给对应的连接发送消息
wsServer.to(json.id).emit('clientFun', event.data)
});
// 当关闭连接后触发 disconnect 事件
wsServer.on('disconnect', function () {
console.log('断开一个连接。');
});