我正在实时(套接字)写一个绘图板(画布)!在一台笔记本电脑上,如果您同时以多个用户的身份登录以检查板子,则板子工作正常。如果我通过另一台连接到同一个 wi-fi 的笔记本电脑,那么另一台笔记本电脑将无法连接到服务器。显示错误 ERR_CONNECTION_REFUSED。你能建议我做错了什么吗?
服务器代码:
const express = require('express')
const app = express()
const socketIO = require('socket.io')
const http = require('http').createServer(app)
const io = socketIO(http, {
cors: {
origin: "*",
},
})
const port = 3000
io.on('connection', (socket) => {
console.log(`${socket.id} has connectd`)
socket.on('openRoom', (room) => {
socket.join(room)
socket.on('draw', (data) => {
socket.broadcast.to(room).emit('data', { x: data.x, y: data.y, strokeWidth: data.strokeWidth, strokeColor: data.strokeColor })
})
})
socket.on('disconnect', (socket) => console.log(`${socket.id} has disconnected`))
})
http.listen(port, () => {
console.log(`server has been started on port ${port}`)
})
里面的一段客户端代码:
created () {
this.socket = io('http://127.0.0.1:3000')
this.socket.on('connect', () => {
console.log('connected', this.socket)
this.socket.emit('openRoom', roomNumb)
})
},
methods: {
mousedown (e) {
this.isDrawing = true
const rect = this.canvas.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
this.startX = x
this.startY = y
this.context.beginPath()
this.context.moveTo(this.startX, this.startY)
},
mousemove (e) {
const rect = this.canvas.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
const strokeWidth = this.currentWidth
const strokeColor = this.colorArray[this.currentColor]
if (this.isDrawing) {
this.socket.emit('draw', { x, y, strokeWidth, strokeColor })
this.context.lineTo(x, y)
this.context.lineWidth = strokeWidth
// this.context.globalCompositeOperation = 'source-over'
this.context.lineCap = 'round'
this.context.strokeStyle = strokeColor
this.context.stroke()
this.startX = x
this.startY = y
this.points.push({
x: x,
y: y
})
}
},
mouseup (e) {
this.allPoints.push(this.points)
console.log(this.allPoints)
this.isDrawing = false
this.points = []
},
toGetPoints: function () {
this.socket.on('data', ({ x, y, strokeWidth, strokeColor }) => {
this.context.lineTo(x, y)
this.context.lineWidth = strokeWidth
this.context.lineCap = 'round'
this.context.strokeStyle = strokeColor
this.context.stroke()
})
}
}
看看你是不是认真的。
客户专线:
这意味着客户端正在连接
localhost,或者换句话说,在您的代码中它说“客户端和服务器必须在同一台计算机上”!如果您真的在客户端中准确地写了,那么这是第一个更正它的地方。
尝试将服务器放在某台计算机上,然后在本地网络中查找其地址(例如,在 wifi 内)
在 Windows 上,这是通过 command 完成的
ipconfig,在 Linux 上 - 类似于ip a或ifconfig假设您已将运行服务器的计算机的地址定义为
192.168.1.101. 尝试将此特定地址设置给客户端,然后客户端应该可以在多台计算机上正常工作。如果它“不起作用” - 你需要寻找原因,最有可能的原因是防火墙!
总的来说,我认为开始就是这样。只要它在本地工作,就可以将服务器带到互联网上,然后你可以写另一个问题。