Socket.io does not run as expected on Heroku

Issue

This Content is from Stack Overflow. Question asked by Captai-N

everyone. I’m having an issue with Socket.io on Heroku. Everything runs wonderfully on my local machine, which means: I can see when a user makes an entry and it arrives just-in-time => both clients can see the message real-live!
However, it doesn’t work on Heroku. A client doesn’t see whether the other party makes an input, let alone the message comes just-in-time. Only after refreshing the page. Here is my code:

This is my server code:

 const PORT = 2900;

 const server = http.createServer(app);
 const socketio = new Server(server, { cors: { origin: "*" } });


  socketio.on("connect", (socket) => {
  socket.on("addUser", (userId) => {
  addUser(userId, socket.id);

//socketio.emit("getUsers", users);
});

//tipping
socket.on("typing", ({ receiverId, senderId, text, tippt }) => {
const user = getUser(receiverId);

if (user)
  socketio.to(user.socketId).emit("userIsTyping", {
    senderId,
    text,
    tippt,
   });
});

//send and get message
socket.on("sendMessage", ({ receiverId, senderId, text }) => {
const user = getUser(receiverId);

if (user)
  socketio.to(user.socketId).emit("getMessage", {
    senderId,
    text,
  });
});

//when disconnect
socket.on("disconnect", () => {
removeUser(socket.id);
socketio.emit("getUsers", users);
 });
});


server.listen(PORT, () => console.log(`Listening on port ${PORT}`));

And that’s the client code:

const socket = useRef();

useEffect(() => {
socket.current = io(":2900");

socket.current.on("getMessage", (data) => {
  setArrivalMessage({
    sender: data.senderId,
    text: data.text,
    createdAt: Date.now(),
  });
});
socket.current.on("userIsTyping", (data) => {
  setGibtEin(data.tippt);
  setAnUser(data.senderId);
});
}, []);



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?