zoukankan      html  css  js  c++  java
  • [Node.js]30. Level 6: Listen 'Question' from client, and then Answer the Question

    Clients can also answer each other questions, so let's build that feature by first listening for the'answer' event on the client, which will send us both the question and answer, which we want to broadcast out to the rest of the connected clients.

    var express = require('express');
    var app = express.createServer();
    var socket = require('socket.io');
    var io = socket.listen(app);
    
    io.sockets.on('connection', function(client) {
      console.log("Client connected...");
    
      // listen for answers here
    
      client.on('question', function(question) {
        client.get('question_asked', function(err, asked) {
          if(!asked) {
            client.set('question_asked', true);
            client.broadcast.emit('question', question);
          }
        });
    //can pass two or more params in callback function client.on(
    'answer', function(question,answer) { client.broadcast.emit('answer',question, answer); }); }); });

    Now on the client, listen for the 'answer' event and call the answerQuestion function, passing in both the question and the answer that was broadcasted from the server.

    <script src="/socket.io/socket.io.js" />
    
    <script>
      var server = io.connect('http://localhost:8080');
    
      server.on('question', function(question) {
        insertQuestion(question);
      });
    
    server.on('answer', function(question, answer){
        answerQuestion(question, answer);
    });
        
      //Don't worry about these methods, just assume 
      //they insert the correct html into the DOM
      // var insertQuestion = function(question) {
      // }
    
      // var answerQuestion = function(question, answer) {
      // }
    </script>
  • 相关阅读:
    转载.net泛型理解说明
    转载Repository 和Unit of work的使用说明
    libtool的工作原理
    带有通配符的字符串匹配算法-C/C++
    linux core文件机制
    grep多条件和sed合并两行
    BZOJ 3232 圈地游戏 (分数规划 + SPFA找负/正环)
    CSP2019 D1T3 树上的数 (贪心+并查集)
    CSP-S 2019 第二轮 退役记
    object-c中的int NSInteger NSUInteger NSNumber辨析
  • 原文地址:https://www.cnblogs.com/Answer1215/p/3881423.html
Copyright © 2011-2022 走看看