[Node.js] Level 6. Socket.io

6.2 Setting Up socket.io Server-Side

So far we've created an Express server. Now we want to start building a real-time Q&A moderation service and we've decided to use socket.io.

Using the http module, create an new http server and pass the expressapp as the listener for that new server.

var express = require('express');
var app = express();
var server = require('http').createServer(app);

Using the socket.io module, listen for requests on the http server. Store the return object of this operation in a variable called io.

var io = require('socket.io')(server);

Use the object stored in io to listen for client 'connection' events. Remember, the callback function takes one argument, which is the client object that has connected.

When a new client connects, log a message using console.log().

io.on('connection', function(client){
    console.log(client + "has connected.");
});

Finally, we want to tell our http server to listen to requests on port 8080.

server.listen(8080);

 

Code:


复制代码
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

io.on('connection', function(client){
    console.log(client + "has connected.");
});

server.listen(8080);
复制代码

 

6.3 Client socket.io Setup 

In our html file, load the socket.io.js script and connect to the socket.io server.

Load the socket.io.js script. The socket.io.js path you should use is'/socket.io/socket.io.js'. Express knows to serve the socket.io client js for this path.

Using the global io object that's now available for us, connect to the socket.io server at http://localhost:8080.

<script src="/socket.io/socket.io.js"></script>

<script>
  var server = io.connect('http://localhost:8080');
</script><script></script>

 

6.4 Listening For Questions

In our client below, listen for 'question' events from the server and call the insertQuestion function whenever the event fires.

First, listen for 'question' events from the server.

Now, have the event callback function call the insertQuestion function. TheinsertQuestion function is already created for you, and it's placed in its own file. It expects exactly one argument - the question.

  server.on('question', function(data){
      insertQuestion(data);
  }); 

 

Code: 


复制代码
<script src="/socket.io/socket.io.js"></script>
<script src="/insertQuestion.js"></script>

<script>
  var server = io.connect('http://localhost:8080');

  // Insert code here
  server.on('question', function(data){
      insertQuestion(data);
  });       
</script>
复制代码

 

6.5 Broadcasting Questions

When a question is submitted to our server, we want to broadcast it out to all the connected clients so they can have a chance to answer it.

In the server, listen for 'question' events from clients.

  client.on('question', function(question){
  
  });

Now, emit the 'question' event on all the other clients connected, passing them the question data.

client.broadcast.emit('question', question);

 

Code:


 

复制代码
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

io.on('connection', function(client) {
  console.log("Client connected...");
  
  client.on('question', function(question){
      client.emit('question', question);
  });
});

server.listen(8080);
复制代码

 

6.6 Saving Client Data

In our real-time Q&A app, we want to allow each client only one question at a time, but how do we enforce this rule? We can use socket.io's ability to save data on the client, so whenever a question is asked, we first want to check the question_asked value on the client.

First, when a client emits a 'question' event, we want to set the value ofquestion_asked to true.

Second, when a client emits a 'question' event, we want to broadcast that question to the other clients.

client.question_asked = true;
client.broadcast.emit('question', question);

Finally, when a client emits a 'question' event, check to make surequestion_asked is not already set to true. We only want to allow one question per user, so make sure that we only set the value ofquestion_asked and broadcast the question to other clients when the value of question_asked is not already true.

复制代码
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

io.on('connection', function(client) {
  console.log("Client connected...");

  client.on('question', function(question) {
    if(!client.question_asked){
      client.question_asked = true;
       client.broadcast.emit('question', question);
    }
  });
});

server.listen(8080);
复制代码

 

6.7 Answering Questions 

Clients can also answer each other's 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.

With the client, listen for the 'answer' event from clients.

    client.on('answer', function(question, answer){

    });

Now, emit the 'answer' event on all the other clients connected, passing them the question data.

  // listen for answers here
    client.on('answer', function(question, answer){
            client.broadcast.emit('answer', question, answer);
    });

 

6.8 Answering Question Client 

Now on the client, listen for the 'answer' event and then broadcast both the question and the answer to the connected clients.

Listen for the 'answer' event off of the server.

Call the answerQuestion function, passing in both the question and theanswer that was broadcast from the server.

复制代码
<script src="/socket.io/socket.io.js"></script>

<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>
 
复制代码

 

posted @   Zhentiw  阅读(942)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示