如何在调用socket.emit之前从socket.on获取响应

时间:2013-11-08 18:15:58

标签: node.js socket.io

我正在使用node.js来创建一个维护课程存储库及其各自讲座和幻灯片的应用程序。学生课程的转录(来自mysql Db)是基于学生的名字,讲座的回顾是基于课程名称和soo。学生姓名存储在服务器上,我必须在调用服务器获取课程列表之前获取它。

这是我的代码,有更多解释:

 var StdName;
 $(document).ready(function () {

    //connect to server
        connectBind();
    var socket = $("#click").data();
    /**********Query database For student name!!!**********/
    try {
    socket.emit('askStdName');
    }
    catch (err) {
    alert(err.message);
        }

        /********Query database For Courses!!!************/
    try {

    socket.emit('view-contents', StdName);
        }
        catch (err) {
        alert(err.message);
    }

});

    //connecting to server
function connectBind() {
    // connect to server on this port.
    var socket = io.connect('http://localhost:3000');
$("#click").data(socket);

/**********GETTING NAME OF STUDENT*********/ //I WANT TO GET STUDENT NAME BEFORE THE QUERY FOR COURSES GET CALLED
try {
     socket.on('get-Studentname', function (data) {
     StdName = data;
     alert("StdName: " + StdName);
                });
}
catch (err) {
     alert(err.Message);
}

这是服务器端脚本:

    var express = require('express'); //load express
    var http = require('http'); // then http
    var socketIO = require('socket.io'); // then socket
    var mysql = require('mysql');
    var nodemailer = require("nodemailer");


    var client = mysql.createConnection({
          host: 'localhost',
          user: 'root',
          password: '',
      database: 'smartboard_db'
    });

    client.connect();

    var app = express(); // create application
    var server = http.createServer(app); //create server
    var io = socketIO.listen(server); // start listening to server.
    io.set('log level', 2);

   // setup routing for static files.       
   app.use(express.static(__dirname + '/public'));

   //start server
   server.listen(3000, function(){
   console.log('Server running...');
   });

   // First page  
   app.get('/', function(request, response) {
   response.sendfile(__dirname + '/student-home.html');
   });

   io.set('log level', 1);
   io.sockets.on('connection', function (socket) {
   var sucess;
   console.log("client connected");

/************SENDING THE NAME TO CLIENT*************/
socket.on('askStdName', function () {
    console.log('sending student name to client');
    socket.emit('get-Studentname', stdName);
    });

/***********CHANNEL FOR GETTING COURSE LIST************/
socket.on('view-contents', function (stdName) {
    //console.log("this is what I get from client for courses: " + stdName);
    var DATABASE = 'smartboard_db';


    client.query('USE ' + DATABASE);


    /*****QUEURY FOR COURSES *****************/
    client.query('SELECT courses FROM student_info WHERE name = "' + stdName + '"',                           function (err, results) {
        if (err) {
            throw err;
        }
        else {
            console.log(JSON.stringify({ courses: results }));
            socket.emit('courses', JSON.stringify({ courses: results }));
        }
    });

       });
   });

请帮忙吗?

1 个答案:

答案 0 :(得分:3)

如果get-Studentname事件

// request student name
socket.emit('askStdName');

// wait for the student name to be returned, followed by requesting the courses
socket.on('get-Studentname', function (StdName) {
  socket.emit('view-contents', StdName);
});

或者,您可以传递一个带有学生姓名请求的函数,服务器可以调用该函数来发回响应(而不是让服务器发出响应)。这确实需要在服务器上进行不同的设置:

// client code
socket.emit('askStdName', function(StdName) {
  socket.emit('view-contents', StdName);
});

// server code should look like this:
socket.on('askStdName', function(done) {
  // get student name (depends on your setup)
  ...
  // call the function to return the value
  done(StdName);
});