Below we've already created an express server, but we want to start building a real-time Q&A moderation service and we've decided to use socket.io.

Require socket.io and make sure it listens for requests on the express app.

Also, print out a message to the console whenever a new socket.io client connects to the server.

app.js

var express = require('express');
var socket = require('socket.io');
var app = express.createServer();
var io = socket.listen(app); io.sockets.on('connection', function(client){
console.log("Welcome...");
});

In our html file, load the socket.io.js script and then use io.connect to connect to socket.io on the server. Connect to the server at http://localhost:8080.

Tip: 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.

index.html

<script src="/socket.io/socket.io.js"></script>
<script>
// use the socket.io server to connect to localhost:8080 here
var server = io.connect('http://localhost:8080');
</script>

In our client below, listen for 'question' events from the server and call the insertQuestionfunction whenever the event fires. The insertQuestion function is already created for you, and it's placed in its own file. It expects exactly one argument - the question.

index.html

<script src="/socket.io/socket.io.js" />
<script src="/insertQuestion.js" /> <script>
var server = io.connect('http://localhost:8080'); // insert code here
server.on('question', function(data){
insertQuestion(data);
});
</script>

insertQuestion.js

var insertQuestion = function(question){
var newQuestion = document.createElement('li');
newQuestion.innerHTML = question; var questions = document.getElementsByTagName('ul')[0];
return questions.appendChild(newQuestion);
}

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 below, listen for 'question' events from clients and then emit the 'question' event on all the other clients connected, passing them the question data.

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 here
client.on('question', function(question){
//All client, so it is broadcast
client.broadcast.emit('question', question);
});
});

In our real-time Q&A app, we want to allow each client only 1 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. If it's not already set to true, broadcast the question and then go ahead and set the value to true.

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..."); client.on('question', function(question) {
client.get('question_asked', function(err, asked){
if(!asked){
client.broadcast.emit('question', question);
client.set('question_asked', true);
}
});
});
});

[Node.js]29. Level 6: Socket.io: Setting up Socket.io server-side & Client socket.io setup的更多相关文章

  1. [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 ...

  2. C Socket Programming for Linux with a Server and Client Example Code

    Typically two processes communicate with each other on a single system through one of the following ...

  3. [Node.js]33. Level 7: Persisting Questions

    Let's go back to our live-moderation app and add some persistence, first to the questions people ask ...

  4. [Node.js]31. Level 7: Redis coming for Node.js, Simple Redis Commands

    Let's start practicing using the redis key-value store from our node application. First require the  ...

  5. [Node.js]24. Level 5: Express, Express routes

    Create an express route that responds to GET requests at the URL /tweets that responds with the file ...

  6. [Node.js]23. Level 4: Semantic versioning

    Update the versions on your dependencies to be a little more flexible, adding the ~ in front of your ...

  7. [Node.js]22. Level 4: Dependency

    Add two dependencies to your package.json file, connect and underscore. You'll want to useconnect ve ...

  8. [Node.js]32. Level 7: Working with Lists -- Redis

    As we saw in the video, redis can do more than just simple key-value pairs. We are going to be using ...

  9. [Node.js]28. Level 5: Express Server

    Now let's create an express server which queries out for this search term and just returns the json. ...

随机推荐

  1. ubuntu搭建php运行环境

    sudo apt-get install apache2sudo apt-get install php7.0php -v 查看PHP是否安装成功sudo apt-get install libapa ...

  2. php安装编译时 configure: error: Cannot find OpenSSL's <evp.h>

    =============================================== yum install error: protected multilib versions error ...

  3. 本地文件包含漏洞(LFI漏洞)

    0x00 前言 本文的主要目的是分享在服务器遭受文件包含漏洞时,使用各种技术对Web服务器进行攻击的想法. 我们都知道LFI漏洞允许用户通过在URL中包括一个文件.在本文中,我使用了bWAPP和DVW ...

  4. python开发_thread_线程基础

    说到线程,我们要知道啥是串行,啥是并行程序 举个例子: 串行程序,就是一个一个的执行程序 #python threading import time ''' 每一秒中,输出:this is a dem ...

  5. python开发_webbrowser_浏览器控制模块

    ''' python的webbrowser模块支持对浏览器进行一些操作 主要有以下三个方法: webbrowser.open(url, new=0, autoraise=True) webbrowse ...

  6. BZOJ 4408: [Fjoi 2016]神秘数 可持久化线段树

    4408: [Fjoi 2016]神秘数 题目连接: http://www.lydsy.com/JudgeOnline/problem.php?id=4408 Description 一个可重复数字集 ...

  7. hdu 4163 Stock Prices 花式排序

    Stock Prices Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Tot ...

  8. MySQL DB 主从复制之SSL

    需求架构 准备工作 主从服务器时间同步 # 主从服务器同时配置crontab任务,与NTP服务器同步时间即可 */5 * * * * ntpdate 172.16.0.1 &>/dev/ ...

  9. 特殊字符\u2028导致的Javascript脚本异常

    这原本是个小错误,但排查花了不少时间,因此写下来和大家分享一下. 起因 通过Ajax动态从后台读取文章内容,并显示在页面上,加载到某篇文章的时候,报javascript语法错误,无法显示文章内容. A ...

  10. 5V and 3V Level Translators

    http://www.daycounter.com/Circuits/Level-Translators/Level-Translators.phtml Interfacing 5V and 3V l ...