Hello friends I?m new here and I found with a hard issue, I have used Socket IO Client in react js without any problem, the same syntax i used with Gatsby and I find this problem. My node js server doesn't detect when a new client has joined.
This my script.
React JS Component (Works)
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;
With GatsbyJS Component (not working)
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
As you see, both have the same script or the same logic about socket io usage, but I don't know why in react works and gatsbyjs not. Maybe is a bug or what's the problem?
Server (No problem)
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)
})
})
Thanks for your support :)
I solved this, the issue was the package version on client side I changed to "2.2" because the previous "2.3" wasn't working with my logic, it works now :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With