Не подключается к серверу сокета
Пишу доску рисования (canvas) в реальном времени(socket)! На одном ноуте если войти от имени нескольких пользователей в одно время, чтобы проверить доску, то доска работает нормально. А если я захожу через другой ноут, который подключен к тому же 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()
})
}
}
Ответы (1 шт):
Посмотрите, пожалуйста, действительно ли Вы это имели в виду.
Строка клиента:
this.socket = io('http://127.0.0.1:3000')
Это означает, что клиент подключается к localhost, или, другими словами, что у Вас в коде написано "клиент и сервер должны быть на одном компьютере"!
Если Вы действительно именно так написали в клиенте - то это первое место на исправление.
Попробуйте поставить сервер на какой то компьютер, а потом узнать его адрес в локальной сети (например, в пределах wifi)
На Windows это делается командой ipconfig, на линукс - чем то вроде ip a или ifconfig
Предположим, Вы определили адрес компа, на котором запущен сервер, как 192.168.1.101. Попробуйте именно этот адрес пропсиать в клиента, и тогда клиент должен нормально заработать с нескольких компьютеров.
Если это "не работает" - надо искать причину, скорее всего, причина - это файервол!
В общем, думаю, что начало - именно такое. Как только заработает в пределах локалки - можно будет выводить сервер в интернет, можете тогда написать еще один вопрос.