I am working on a node JS application, where I am trying to use socket.io following this tutorial. Until this tutorial everything is fine, even the client is connected to the server through the socket, as it display a message on connection. But I don't know why my code isn't working on emit, and on event, and event handler.
Below is my Code on server side :
const express = require("express"); const app = express(); const scrap = require("./algorithm"); const mysql = require("mysql"); const ms_connect = mysql.createConnection({ host:'localhost', user:'root', password:'', database:'scrapper_db' }); const server = app.listen(8000, function(){ console.log('Listening on 8000'); }); const io = require("socket.io").listen(server); app.use(express.static(__dirname + "/")); io.on("connection",function(socket){ console.log("Sockets Connection Made ! " + socket.id); socket.emit("testing",{data:"I am tested"}); io.on("disconnect",function(){ console.log("Client Disconnected !"); }) }) //mySQL Conection ms_connect.connect(function(err){ if(err) console.log(err); ms_connect.query("Select * FROM test",function(err,rows,fields){ if(err) console.log("Error Executing Query"); }) }) app.get("/scrap",function(req,res){ res.sendFile(__dirname+"/index.html"); }) Client side code :
var socket = io.connect('http://localhost:8000/scrap'); console.log(socket.connected); //returns false :( socket.on("testing", function(d) { console.log(d); }); In the client side, the
socket.connectedobject returnsfalse, but on server side it says connected. I don't know how , and I am using third link from this socket.io cdnjs server.
app.get("/scrap",func)@RaphaelFacredynsocket.on('connect', () => { console.log(socket.connected); // true });rather than just loggingsocket.connectedAlso what happens if you just usevar socket = io.connect();on your client side code