Привет, друзья! Я новичок здесь и обнаружил, что возникла серьезная проблема. Я использовал Socket IO Client в реакции js без проблем, тот же синтаксис, который я использовал с Gatsby, и я обнаружил эту проблему. Мой node js сервер не определяет, когда к нему присоединился новый клиент.
Это мой скрипт.
Реагирует JS Компонент (Работает)
import React, { useEffect } from 'react';
import './App.css';
// socket
import socketIOClient from 'socket.io-client';
const socketEndPoint = 'http://localhost:32/';
const ioSocket = socketIOClient(socketEndPoint);
// nameSpace: public_chat
const ns= 'public_chat';
const salaSocket = socketIOClient(socketEndPoint + ns)
const messageKey = 'test_message'; // Message id
function App() {
function sendMessage(){
salaSocket.emit(messageKey, 'Prueba de mensaje desde el cliente: '+Math.random())
}
function recepMessage(){
salaSocket.on(messageKey, (received) => {
alert('Message: '+ received)
})
}
useEffect(() => recepMessage() , [])
return (
<div className="App">
<button style={{marginTop: '50', padding: '10px'}} onClick={sendMessage}>
Send message
</button>
</div>
);
}
export default App;
С Гэтсби JS Компонент (не работает)
import React, { useEffect } from 'react'
import './Chat.scss'
import { Button } from '@material-ui/core'
import socketIOClient from 'socket.io-client'
const socketEndPoint = 'http://localhost:32'
const sala = 'public_chat'
const salaSocket = socketIOClient(socketEndPoint + sala)
const messageKey = 'test_message'
function Chat() {
function initSocket() {
salaSocket.on(messageKey, received => alert('Message received: '+ received))
}
function sendMessage() {
salaSocket.emit(messageKey, `Send a message to server`)
}
useEffect(() => {
initSocket()
}, [])
return(
<div className='chat'>
<Button onClick={sendMessage}>send</Button>
</div>
)
}
export default Chat
Как видите, у обоих одинаковые сценарии или одинаковые логики c об использовании сокетов io, но я не знаю, почему в программе работает, а gatsby js нет. Может быть, это ошибка или в чем проблема?
Сервер (нет проблем)
const express = require('express')
const http = require('http')
const socketIo = require('socket.io')
const PORT = process.env.PORT || 32
const app = express()
const server = http.createServer(app)
const io = socketIo(server, {origins: '*:*'})
app.get('/', (req, res) => res.sendFile(`${__dirname}/index.html`))
server.listen(PORT, () => console.log(`Socket runing at port: ${PORT}`))
const sala = io.of('public_chat')
const messageKey = 'test_message'
sala.on('connection', socket => {
console.log('New user connected', socket.id)
socket.on(messageKey, data => {
console.log('received: ', data)
sala.emit(messageKey, data)
})
})
Спасибо за вашу поддержку:)