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. WEB架构师成长之路 三

    Web架构师究竟都要学些什么?具备哪些能力呢?先网上查查架构师的大概的定义,参见架构师修炼之道这篇文章,写的还不错,再查查公司招聘Web架构师的要求. 总结起来大概有下面几点技能要求: 一. 架构师有 ...

  2. zoj 3537 区间dp+计算几何

    题意:给定n个点的坐标,先问这些点是否能组成一个凸包,如果是凸包,问用不相交的线来切这个凸包使得凸包只由三角形组成,根据costi, j = |xi + xj| * |yi + yj| % p算切线的 ...

  3. 【洛谷】1852:[国家集训队]跳跳棋【LCA】【倍增?】

    P1852 [国家集训队]跳跳棋 题目背景 原<奇怪的字符串>请前往 P2543 题目描述 跳跳棋是在一条数轴上进行的.棋子只能摆在整点上.每个点不能摆超过一个棋子. 我们用跳跳棋来做一个 ...

  4. BZOJ 2142 礼物 组合数学 CRT 中国剩余定理

    2142: 礼物 Time Limit: 10 Sec  Memory Limit: 259 MBSubmit: 1450  Solved: 593[Submit][Status][Discuss] ...

  5. 使用python解决烦人的每周邮件汇总!

    最近开始接手BI工作,其中又一个繁琐又不得不做的事,就是每周五都得汇总上个财务周的数据给运营人员! 作为一个懒人,只能把这件事交由电脑去处理了. 初步的idea:周五11点前mac自动执行汇总程序-& ...

  6. 使用清华大学开源软件镜像AOSP的“每月更新初始化包”更新指定版本的Android源码

    参照官方教程:Tsinghua Open Source Mirror 1. 下载了repo工具 mkdir  ~/bin PATH = ~/bin:$PATH curl  https://storag ...

  7. SVN服务端的版本对比及创建仓库时的注意事项

    SVN是一个开放源代码的版本控制系统,分为客户端和服务端.就windows系统而言,客户端通常使用 TortoiseSVN,下载地址:https://tortoisesvn.net/  ,而服务端通常 ...

  8. QQclient团队博客

    Windows 8 视频採集  http://impd.tencent.com/?p=25 句柄泄漏检測工具的实现原理 http://impd.tencent.com/?p=29

  9. 深入浅出VC++串口编程之基于Win32 API

    1.API描述 在WIN32 API中,串口使用文件方式进行访问,其操作的API基本上与文件操作的API一致. 打开串口 Win32 中用于打开串口的API 函数为CreateFile,其原型为: H ...

  10. 使用Bootstrap 3开发响应式网站实践02,轮播

    本篇体验图片轮播.html部分为: <div class="carousel slide" id="myCarousel" > <!--Ind ...