Question

I'm just getting into coding server side javascript and have been reading tutorials on socket.io and node.js, but I haven't come across anything demonstrating how to use node.js to access a mysql database.

Say for instance I want to create a method that listens to a table in my database at mysql.something.com (with database: database, username: username, etc), how would I get socket.io with node.js to connect to that database and listen for new input to that table and then subsequently return that input?

I'm wondering if anyone could give me a specific example that uses a publish subscribe model.

Thanks for the help.

Était-ce utile?

La solution

You have to poll mysql database for changes at regular interval and when detect a change emit a socket.io event. Here's a pseudo code

var mysql = require('mysql');
var connect = mysql.createConnection({
      host: 'localhost'
    , database: 'your_database'
    , username: 'user'
    , password: 'password'});

var initial_result;

// check for changes after 1 second

setTimeout(function(){

    connect.query('select * from your_table', function(err, result) {
        if(err) { throw new Error('Failed');}
        initial_result = initial_result || result;

        if(Changed(initial_result, result)) { socket.emit('changed', result); }

    });

    function Changed(pre, now) {
  // return true if pre != now
    }


}, 1000); 

Autres conseils

I don't if you have already solve your question, but yesterday i also came alogn with this problem.. I want to see an example of node.js, socket.io and mysql. So i searched a lot on youtube and found only this.. https://www.youtube.com/watch?v=Pw_AhwvxU58.

I hope i helped you somehow.

I was wondering if this was at all possible with handling user logins? I'm trying to create a chatroom where users can sign up and log in and then begin chatting. I'm having trouble pulling the username to pass through the socket chat system.

> `  passport.use(new JWTStrategy({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: process.env.SECRET
}
  , async function ({ id }, cb) {
    try {
      const user = await User.findOne({ where: { id }, include: [Post] } )
      cb(null, user)
      socket.emit('username', user.User.username)
    } catch (err) {
      cb(err, null)
    }
  }))`

This is just my shitty attempt at emitting the username after reading what you guys posted above. I'm not sure if this would even work but I'm wondering if Pulling out the user.User.username from this async function and emitting it to socket would allow me to then use the users name in the chat.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top