const server = require('http').createServer() const socketIo = require('socket.io')(server) const CreatePoint = require('./CreatePoint.js') // 全部已鏈接的客戶端 socketIo.on('connection', (client) => { // console.log(client) // 斷開時刪除 client.on('disconnect', () => { // 。。。 }) // 當客戶端觸發setPoint事件以後,socket就向客戶端推送新的座標 client.on('setPoint', (point) => { console.log(point) // 1. 建立一個創造座標的實例 let CreateCustomPoint = new CreatePoint(point) // 每隔3秒向客戶端推送一次座標 setInterval(() => { client.emit('newPoint', CreateCustomPoint.randomAction()) }, 3000) }) }) server.listen(3000, '192.168.1.202', () => { console.log('this server is listening on port 3000') })
先須要鏈接到socket前端
import VueSocketIo from 'vue-socket.io' Vue.use(new VueSocketIo({ debug: true, // 這裏的地址就是後端地址 connection: '192.168.1.202:3000', vuex: { store, actionPrefix: 'SOCKET_', mutationPrefix: 'SOCKET_' } // options: { path: "/my-app/" } }))
sockets: { // socket服務器鏈接時觸發 connect: () => { console.log('已成功鏈接到socket服務器') }, // 接收socket服務器推送的newPoint事件 newPoint(point) { console.log(`接收到socket服務器的新座標${point}`) // console.log(this) this.points.push(point) // 關閉原來的標誌物 this.mkrTool.close() this.map.clearOverlays() // this.map.centerAndZoom(point, 15) // 在新座標添加覆蓋物 this.freshOverlay(point) } },
github: https://github.com/lyttonlee/...vue