SOuřaan Gřg SOuřaan Gřg - 6 months ago 84
JSON Question

How to use a json data for socket emit from client side?

What is the best method to use a mysql fetched data during socket emiting time?
For example, I will have a data retrieved from database and now I would like to use that data on

socket.emit('emit_name', function(data){ })
.What will be the best way?

I firstly, tested with easy way to find if it works or not rather then diving beginning into complicated one from json.I used two data as 'type' and 'fruit' something like this on "Client side"

var socket = io.connect( 'http://localhost:8080' );
var nameVal = "Type";
var msg = "apple";

socket.emit( 'messages', { type : nameVal, fruit: msg } );


on Server side

var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var app = express();
var mysql = require('mysql');
var server = http.createServer( app );
var io = socket.listen( server );
var pool = mysql.createPool({
connectionLimit : 10,
host: "localhost",
user: "root",
password: "",
database: "mydb"
}
);


io.sockets.on( 'connection', function() {

console.log( "User connected..!" );

io.client.on( 'messages', function(data) {
console.log( 'Message received ' + data.type + ":" + data.fruit );

});

});

server.listen(8080);


After doing this all I just started my node server and I get "connected" on my socket on page load but my work on socket side isn't working at all as I wised.The result(problem) on socket part of server side gives this error as below image :-

enter image description here

What might be the problem?How can I solve this issue?

Answer

This code is just wrong:

io.sockets.on( 'connection', function() {

console.log( "User connected..!" );

io.client.on( 'messages', function(data) {
console.log( 'Message received ' + data.type + ":" + data.fruit );

  });

});

It should be this:

io.on( 'connection', function(socket) {

    console.log( "User connected..!" );

    socket.on( 'messages', function(data) {
        console.log( 'Message received ' + data.type + ":" + data.fruit );
    });
});

You have to use the socket variable that is passed to the io.on('connection, ...)` event to set event handlers on the newly connected socket.


In addition, this line of your client code:

socket.emit( 'messages', { type : nameVal, fruit: msg } );

may be running too soon before the socket has finished connecting. io.connect() is asynchronous. It does not complete immediately. If you try to send data before it is connected, then there is not yet a live socket to actually send the data on. It's possible that socket.io will cache that data until the socket connects (you'd have to check the socket.io code to see for sure), but it is much safer to wait for the connect event on the socket before sending data.