I'm not able to connect to socket on client for some reason. Logging socket all the time returns False. I tried official Socket.io app and it is working fine.. Can anyone help and let me know what I'm missing here?
Server
const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')()
const router = require('./router')
const PORT = process.env.PORT || 8080
io.on('connection', (socket) => {
console.log('user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
})
})
app.use(router)
app.listen(PORT, () => {console.log(`Server running on port ${PORT}`)})
Client
import queryString from 'query-string'
import io from 'socket.io-client'
let socket;
const Chat = () => {
const ENDPOINT = 'http://localhost:8080'
useEffect(() => {
socket = io(ENDPOINT)
console.log(socket);
})
return (
<div>
Chat
</div>
)
}
export default Chat
Solution
Server is listening on app instead http.listen(...)
You should pass http into socket.io:
const io = require('socket.io')(http);
Try using your ip address instead of the localhost
Related
I have a simple React JS app connected to a socket io server. Whenever I open the app in the browser, the client sends new connection request to the server every 5 seconds.
server:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('socket id:', socket.id);
})
server.listen(3001, () => {
console.log('Listening on port 3001');
})
client:
import React from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:3001');
const App = () => {
return (
<div>Hi there!</div>
);
}
export default App;
logs on the server:
socket id: ByXQEMgeVaQ5AGw1AAAA
socket id: 8LzNQsyeYq7GSEvqAAAB
socket id: bbuYEs4kKzjxXuBsAAAC
socket id: vwprv4hnJbRlStG4AAAD
I suspect there could be something wrong on my laptop, cause I don't see anything wrong in the code, any ideas?
Thanks in advance
I would recommend calling connect inside a useEffect and return the disconnect method to be called when the component dismounts.
const [socket, setSocket] = useState(null)
useEffect(() => {
const newSocket = io('http://localhost:3001')
setSocket(newSocket)
return socket.disconnect()
}, [])
Can you try to wrap the client side socket creation in a useEffect that only runs once? I'm curious to see if the behavior still appears.
import React from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:3001');
const App = () => {
useEffect(() => {
const socket = io('http://localhost:3001');
}, [])
return (
<div>Hi there!</div>
);
}
export default App;
Actually I just found the root cause, I had a mismatch between my client version and my server version. I updated the client version to v4 and now it is working
Summary
I have basic sample code which works in socket.io 2.3 which does not work in socket.io 3.0, I want to understand what I need to change.
Full Description
I have a node.js / react project and I wanted to use socket.io. To do this, I implemented the example code from this article, using socket.io v3.0.4, which follows.
Server side:
const http = require("http");
const socketIo = require("socket.io");
const port = process.env.PORT || 4001;
const index = require("./routes/index");
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server);
let interval;
io.on("connection", (socket) => {
console.log("New client connected");
if (interval) {
clearInterval(interval);
}
interval = setInterval(() => getApiAndEmit(socket), 1000);
socket.on("disconnect", () => {
console.log("Client disconnected");
clearInterval(interval);
});
});
const getApiAndEmit = socket => {
const response = new Date();
// Emitting a new message. Will be consumed by the client
socket.emit("FromAPI", response);
};
server.listen(port, () => console.log(`Listening on port ${port}`));
Client Side:
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:4001";
function App() {
const [response, setResponse] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("FromAPI", data => {
setResponse(data);
});
}, []);
return (
<p>
It's <time dateTime={response}>{response}</time>
</p>
);
}
export default App;
on the server, I was receiving the error
socket.io:client client close with reason ping timeout
which led me to this article, which implied a version issue.
Based on that, I've attempted a few things, but specifically, I was running socket.io and socket.io-client both version 3.0.4. I uninstalled and reinstalled v 2.3.0/2.3.1. It now works flawlessly.
So my question is: what do I need to change to make this work with the more recent version of socket.io.
I am trying to setup a socket in production like so:
client :
import openSocket from 'socket.io-client';
function handleSomething() {
let socketServer = 'https://staging.app.xxx.eu:9999';
const socket = openSocket(socketServer);
socket.on('calendlyHook', () => {
console.log("*** HERE");
...
socket.emit('closeSocket');
socket.close();
socket.removeAllListeners();
});
}
server :
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
function openSocket() {
io.close();
io.set('origins', '*:*');
io.on('connection', (client) => {
console.log('Socket connected');
client.on('closeSocket', () => {
io.close();
io.removeAllListeners();
console.log('Socket closed');
});
});
const port = 9999;
io.listen(port);
console.log('*** listening on port ', port);
}
Then server-side, another function tries the following:
io.emit('calendlyHook');
or
io.sockets.emit('calendlyHook');
I have several issues in production (none of which happen on localhost):
console.log('*** listening on port ', port) is working fine
console.log('Socket connected') is not happening
io.emit('calendlyHook') or io.sockets.emit('calendlyHook') are not doing anything
I do not have any web server proxy set up on that url.
What is wrong here? Thanks!
I am facing a socket.io connection issue. I know this question is already asked many times. And I tried solutions too from those questions but none of the solution work for me.
Here is my code:
const express = require('express');
var app = express();
var server = app.listen(8000, () => console.log('3000 is the port'));
var io = require('socket.io').listen(server);
const users = {};
io.on('connection', socket => {
console.log('connection ')
if (!users[socket.id]) {
users[socket.id] = socket.id;
}
socket.emit("yourID", socket.id);
io.sockets.emit("allUsers", users);
socket.on('disconnect', () => {
delete users[socket.id];
})
socket.on("callUser", (data) => {
io.to(data.userToCall).emit('hey', {signal: data.signalData, from: data.from});
})
socket.on("acceptCall", (data) => {
io.to(data.to).emit('callAccepted', data.signal);
})
});
Where am I making a mistake?
Your server is running on 8000 port but you logged that it is running on 3000. Hence try connecting it using localhost:8000 connection url.
You can also change server to run on port 3000 instead of 8000.
const PORT=3000;
const server = app.listen(PORT, () => console.log(`${PORT} is the port`));
I'm getting a successful "A user has appeared!" connection message on the back-end. Be there seems to be no communication after the connect event.
Also, the front end keeps disconnecting and reconnecting. Is this bad?
Super socket-io novice here, just started learning tonight.
Thank you in advance for the help.
Node.JS/Express Backend:
const express = require('express')
const server = express();
const http = require('http').createServer(server);
const socketio = require('socket.io');
// ! Express --
server.use(require('cors')());
server.use(express.json());
server.get("/", (req, res) => {
res.status(200).json({
message: `You've hit the socket.io backend!`
})
})
// ! SocketIO
const io = socketio(http);
io.on('connect', socket => {
// ! Emit CheatSheet -> https://socket.io/docs/emit-cheatsheet/
// -> I believe `socket` referes to the open instance of a connection.
// -> This allows us to use functions such as:
// -> .on(eventName, cb(data)) | Use `on` when you are getting data FROM the front end.
// -> .emit(eventName, { data }) | Use `emit` when you are sending data TO the front end.
console.log(`A user has appeared!`)
socket.on("hello", data => console.log(data))
socket.on('disconnect', () => {
console.log(`A user has disappeared.`)
})
});
const PORT = process.env.PORT || 5000;
http.listen(PORT, () => console.log(`Server started on ${PORT}.`));
React Front-End (App.js):
import React, { useEffect, useState } from 'react'
// -> SocketIO
import io from 'socket.io-client';
let socket;
export default () => {
const ENDPOINT = process.env.ENDPOINT || 'http://--server-ip--/'
const [message, setMessage] = useState('Secret Message from the Front-End')
useEffect(() => {
socket = io(ENDPOINT, {
transports: ['websocket']
});
socket.emit('hello', "Hello from the front-end!")
}, [ENDPOINT]);
return (
<div>
<p>{ message }</p>
</div>
)
}
In your client you must wait to the connection be established using the appropriate events before emitting something
useEffect(() => {
socket = io(ENDPOINT, {
transports: ['websocket']
});
socket.on('connect', function(){
socket.emit('hello', "Hello from the front-end!")
});
}, [ENDPOINT]);