I have an application server and client with socket.io, and I'm trying to have a communication between them. Unfortunetely it's not working as expected. In general the process is like.
1 - Initiate server. 2 - Initiate client 3 - Connect client in the server 4 - server receive the message that connect and send a broadcast to client. 5 - client receive message and send back "hello" message and present in the console
step 4 and 5 not working at all. any help?
Codes:
SERVER -----------------------------------------------
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected')
io.emit('broadcast msg from server')
io.on('hello', () => {
console.log('mensagem do client')
io.emit('hello');
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
//Client -----------------------------------------------
const ioClient = io.connect("http://localhost:3000")
const readline = require('readline')
ioClient.on("connect", () => {
console.log('conectou')
});
const rl = readline.createInterface({
input: process.stdin,
utput: process.stdout
});
ioClient.on("broadcast msg from server", () => {
console.log("broadcast msg from server");
ioClient.emit("hello");
});
ioClient.on("hello", () => {
console.log("helloFrom server");
});
I believe you are missing out on the client-side
socket.io-clientas the server-sidesocket.iowill not work on the client side. You'll need to install it first before establishing the connection to the server side.After installing the above, you will have to insert the following line before the first line of
Client.