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 };
};
Related
I'm following this tutorial: https://www.youtube.com/watch?v=tBr-PybP_9c
Locally, the app works fine - I can open up some windows and have them talk to each other. However, when I try to deploy the app to Heroku, the clients no longer connect to the server.
Server-side:
const express = require('express');
const cors = require('cors');
const socket = require('socket.io');
const dotenv = require('dotenv');
dotenv.config({ path: './config.env' });
const app = express();
app.use(cors());
const port = process.env.PORT || 8080;
const server = app.listen(port, () => {
console.log(`App running on port ${port}`);
});
const http = require('http').Server(app);
const io = socket(http, {
pingInterval: 100,
pingTimeout: 500,
cors: {
origin: '*',
},
});
io.listen(server);
io.on('connection', (socket) => {
const id = socket.handshake.query.id;
socket.join(id);
console.log(`A user has connected with ID ${id}`);
});
I deployed the server to a Heroku dyne, and it built successfully. The client is a separate dyne:
import React, { useContext, useEffect, useState } from 'react';
import io from 'socket.io-client';
const SocketContext = React.createContext();
export function useSocket() {
return useContext(SocketContext);
}
export function SocketProvider({ id, children }) {
const [socket, setSocket] = useState();
useEffect(() => {
// const newSocket = io('https://my-heroku-app.herokuapp.com:48600', {
const newSocket = io('http://localhost:8080', {
query: { id },
});
setSocket(newSocket);
return () => newSocket.close();
}, [id]);
return (
<SocketContext.Provider value={socket}>{children}</SocketContext.Provider>
);
}
This also built successfully. Obviously, localhost:8080 doesn't work when deployed to Heroku - I tried using 'https://my-heroku-app.herokuapp.com:48600' (the server application's name plus the port where it's running on Heroku), and that doesn't work either. The console.log never occurs on the server side when I do heroku logs --tail.
Is there a better way to do this? Can I put these into the same app, so I only have to deploy one project?
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
i want to use socket-io in my project and i established it on the server (node-js) and
the client (react) but it seems doesn't work fine and in console on the server i can't see user connected when user connected.
app.js (server):
const express = require("express");
const app = express();
const PORT = process.env.PORT || 5000;
(async () => {
await mongoConnect(error => {
if (error) {
console.log(error);
} else {
const server = app.listen(PORT, () =>
console.log(`server is running on ${PORT} port`)
);
const io = require("./utils/socket-io/socket-io").initialSocket(server);
io.on("connection", socket => {
console.log("user connected");
});
}
});
})();
socket-io.js (server):
const socketIo = require("socket.io");
let io;
module.exports = {
initialSocket: server => {
io = socketIo(server);
return io;
},
getIo: () => {
if (!io) {
throw new Error("no connection to socket-io");
}
return io;
}
};
posts.js (client):
import socketIo from "socket.io-client";
useEffect(() => {
socketIo("http://localhost:5000");
}, [socketIo]);
Edit your app.js to this
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app); // This is going to allow us to create a new web server for express and we're going to it to our express application
const io = socketio(server); // Configure socketio to work with a given server
// Now the server supports websockets
(async () => {
await mongoConnect(error => {
...
else {
io.on("connection", socket => {
console.log("user connected");
});
server.listen(port, () => console.log(`Server is up on port ${port}`));
}
});
})();
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...