I wrote a simple hook to connect react and socket.io:
import io from 'socket.io-client'
import { useEffect, useRef } from 'react'
import { v1 as uuid } from 'uuid';
import { useParams } from "react-router-dom";
const SERVER_URL = 'http://localhost:3001'
export const useSocketConnection = () => {
const { gameId } = useParams()
const userId = uuid()
const socketRef = useRef()
useEffect(() => {
console.log('connectSocket')
socketRef.current = io(SERVER_URL, {
query: { gameId }
})
socketRef.current.emit('join-room', {
userId
})
return () => {
console.log('disconnectSocket')
socketRef.current.disconnect()
}
}, [gameId])
}
the server code is pretty simple:
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app);
const socket = require("socket.io");
const io = socket(server);
const cors = require('cors');
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));
app.get('/', (req, res) => {
res.send('This endpoint works pretty fine')
})
io.on('connection', socket => {
console.log('connected user', socket.id, new Date()) //this log works
socket.on('join-room', () => {
console.log('hope this will work') //doesn't work at all
})
});
server.listen(3001, () => console.log('server is running on port 3001'));
when component renders useEffect hook hires just one time(look screen below)
But server gets one more connection every 5 or 6 seconds I don't know why. If look to the image below each connection has new id and the period of adding new connections is 6 seconds. Also socket.on('join room') doesnt work at all :(
Please help to figure out what Im doing wrong, couldn't find nothing helpful in the internet 🥺🥺🥺.Thank you in advance <3
Related
I am developing a small application in Node.js and React.js I am using sockets for real-time communication in order to update a single value after 10 seconds. The problem is that when I open a new tab in the same browser or when I hit the same URL with the different browser, previously opened tab does not update. I am unable to figure this out why the previously opened tab freezes and the value does not update in it but the value updates in the real time in only newly opened tab. I have attached my code.
Node.js code
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const cors = require('cors')
const port = 8080;
const router = express.Router();
router.get("/", (req, res) => {
res.send({ response: "I am alive" }).status(200);
});
const app = express();
app.use(router);
const server = http.createServer(app);
const io = socketIo(server, {
transports:['polling'],
cors:{
cors: {
origin: "http://localhost:3000"
}
}
});
app.use(cors())
let interval;
io.on("connection", (socket) => {
if (interval) {
clearInterval(interval);
}
interval = setInterval(() => generateValue(socket), 10000);
socket.on("disconnect", () => {
clearInterval(interval);
});
});
const generateValue= socket => {
var min = 100;
var max = 3000;
const Value = Math.floor(Math.random() * (max - min + 1)) + min;
socket.emit("generateValue", Value);
};
server.listen(port, () => console.log(`Listening on port ${port}`));
React.js code
import React from 'react';
import socketIOClient from "socket.io-client";
// import logo from './logo.svg';
// import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
Value: 0,
endpoint: "http://localhost:8080"
};
}
render() {
return (
<div>
<p>{this.state.Value}</p>
</div>
);
}
componentDidMount() {
const socket = socketIOClient(this.state.endpoint);
socket.on("generateValue", data => this.setState({ Value: data }));
}
}
export default App;
You have to modify this variable. So it can save interval individually, per connection.
let interval;
For example:
let intervalsBySocketId = {};
io.on("connection", (socket) => {
const socketId = socket.id;
// these lines is not needed
// if (interval) {
// clearInterval(interval);
//}
intervalsBySocketId[socketId] = setInterval(() => generateValue(socket), 10000);
socket.on("disconnect", () => {
clearInterval(intervalsBySocketId[socketId]);
delete intervalsBySocketId[socketId];
});
});
This is my index.js on the server side
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const PORT = process.env.PORT || 5000;
const router = require('./router');
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
io.sockets.on('connection', (socket) => {
console.log('We have a new connection');
socket.on('join', () => {
console.log(name, room);
});
socket.on('disconnect', () => {
console.log('User left!!');
});
},)
app.use(router);
server.listen(PORT, () => console.log(`Server Started at ${PORT}`));
It throws an error of this function not callable. Also,
This is my Chat.js (Chat Component) on the client-side.
import React, {useState, useEffect} from 'react';
import queryString from 'query-string';
import io from 'socket.io-client';
import './Chat.css';
let socket;
const Chat = ( { location }) => {
const [name, setName] = useState("");
const [room, setRoom] = useState("");
const ENDPOINT = 'localhost:5000';
socket = io.connect(ENDPOINT);
useEffect(() => {
const {name, room} = queryString.parse(location.search);
setName(name);
setRoom(room);
socket.emit('join', { name, room });
}, [ENDPOINT, location.search]);
return (
<h1>Chat</h1>
)
};
export default Chat;
The major problem I am facing here is that the useEffect is getting called multipile times even after I initilaized an array.
What you need to do is to define and connect to it socket-client on App.js instead of initializing it in Chat.js. In Chat.js, you just need to create its object. It should solve the issue of multiple useEffect calls.
**Edit
In App.js add these lines to intialize and connect
import io from 'socket.io-client';
let socket;
const ENDPOINT = 'localhost:5000';
socket = io.connect(ENDPOINT);
And In Chat.js use below code at its respective place to emit events
import io from 'socket.io-client';
let socket;
socket.emit('join', { name, room });
I'm trying to set up a simple socket.io echo server on Heroku using Express and React. The server returns the React site from the build folder, then listens for incoming messages using onAny(). Everything works fine locally, but when deployed to Heroku none of the client-emitted messages are going through after the connection has been established.
I've used Heroku's guide as well as create-react-app and this Medium article as my starting points, and did make sure to turn on http-session-affinity as the Heroku guide said to.
Currently, the React client is set up to emit a fixed message through the onclick handler of a <span>.
Here's the contents of server.js:
'use strict';
const path = require('path');
const express = require('express');
const socketIO = require('socket.io');
const PORT = process.env.PORT || 3000;
const app = express()
.use(express.static('build'))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
const io = socketIO(app);
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
socket.onAny((type, data) => {
console.log('Received:');
console.log(data);
socket.emit('echo', data);
});
});
And here is the client-side React hook that establishes the connection and emits the messages, where I replace [app-name] with the Heroku app name:
import { useEffect, useRef, useState } from "react";
import socketIOClient from "socket.io-client";
const NEW_CHAT_MESSAGE_EVENT = "newChatMessage";
// const SOCKET_SERVER_URL = 'localhost:3000';
const SOCKET_SERVER_URL = 'wss://[app-name].herokuapp.com/sockjs-node';
const useChat = (roomId) => {
const [messages, setMessages] = useState([]);
const socketRef = useRef();
useEffect(() => {
socketRef.current = socketIOClient(SOCKET_SERVER_URL, {
query: { roomId },
});
socketRef.current.on(NEW_CHAT_MESSAGE_EVENT, (message) => {
console.log(message);
const incomingMessage = {
...message,
ownedByCurrentUser: message.senderId === socketRef.current.id,
};
setMessages((messages) => [...messages, incomingMessage]);
});
return () => {
socketRef.current.disconnect();
};
}, [roomId]);
const sendMessage = (messageBody) => {
console.log('sendMessage()');
socketRef.current.emit(NEW_CHAT_MESSAGE_EVENT, {
body: messageBody,
senderId: socketRef.current.id,
});
};
return { messages, sendMessage };
};
I cannot figure out why my React component is not updating once the viewer count changes. When the page first renders, the amount is displayed correctly. Socket events are logged to my terminal also just fine.
There is probably an easy fix to this. What am I doing wrong?
Server
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const port = process.env.PORT || 4001;
const index = require('./index');
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server);
io.on('connection', (socket) => {
console.log('+ client connected');
getApiAndEmit(socket);
socket.on('disconnect', () => {
console.log('- Client disconnected');
getApiAndEmit(socket);
});
});
const getApiAndEmit = (socket) => {
socket.emit('event', io.engine.clientsCount);
};
server.listen(port, () => console.log(`Listening on port ${port}`));
React
import React from 'react';
import socketIOClient from 'socket.io-client';
class App extends React.Component {
constructor() {
super();
this.state = {
response: false,
endpoint: 'http://localhost:4001',
};
}
componentDidMount() {
const { endpoint } = this.state;
const socket = socketIOClient(endpoint);
socket.on('event', (data) => this.setState({ response: data }));
}
render() {
const { response } = this.state;
return (
<p>{response ? <p>Active Users {response}</p> : <p>Loading...</p>}</p>
);
}
}
export default App;
I think the problem is that you're using the wrong type of emit. Take a look at this cheat sheet: https://socket.io/docs/emit-cheatsheet/
If you use socket.emit(), socketio only sends the event to the single, connected client, if you use socket.broadcast.emit(), it emits the event to every client except the sender, and if you use io.emit(), it emits the event to every client.
So I think your code should look something like:
io.on('connection', (socket) => {
io.emit('event', io.engine.clientsCount);
socket.on('disconnect', () => {
socket.broadcast.emit('event', io.engine.clientsCount);
});
});
Try this:
componentDidMount() {
const { endpoint } = this.state;
const socket = socketIOClient(endpoint);
let self = this;
socket.on('event', (data) => self.setState({ response: data }));
}
I am using socket.io to send real-time data from Express Server to Reactjs Client, but the data will be sent only on get request from React client.
The code works perfectly, but when I add routing to Express server and fetch method in client side, it does not work.
server side (server.js) :
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const axios = require("axios");
const PORT = process.env.PORT || 8001;
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.get('/system/overview',(req,res) => {
io.on("connection", socket => {
console.log("New client connected"), setInterval(
() => getAndEmitData(socket),
1000
);
socket.on("disconnect", () => console.log("Client disconnected"));
});
const getAndEmitData = async socket => {
try {
const response = await axios.get(
"https://api.darksky.net/forecast/927aa7bef57ca7b2422"
);
socket.emit("temp", response.data.currently.temperature);
} catch (error) {
console.error(`Error: ${error.code}`);
}
};
})
server.listen(PORT, () => console.log(`Listening on port ${PORT} ...`));
client side ( Overview.js Component ) :
import socketIOClient from "socket.io-client";
...
class Overview extends Component {
constructor() {
super();
this.state = {
response: false,
endpoint: "http://localhost:8001"
};
}
componentDidMount() {
const { dispatch } = this.props;
const { endpoint } = this.state;
dispatch({
type: 'profile/fetchAdvanced',
});
const socket = socketIOClient(endpoint);
fetch('http://localhost:8001/system/overview', {
method: 'get',
})
.then(res => res.json())
.then(data => {
socket.on("temp", data => this.setState({ response: data }));
})
}
...
There is no error but the server does not handle GET request from react client when ComponentDidMount function was executed!
What is the best way to do that ?
Thanks...