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>

[Node.js] Level 6. Socket.io的更多相关文章

  1. node.js中使用socket.io + express进行实时消息推送

    socket.io是一个websocket库,包含客户端的js和服务端的node.js,可以在不同浏览器和移动设备上构建实时应用. 一.安装 socket.io npm install socket. ...

  2. node基于express的socket.io

    前一段事件,我一个同学给他们公司用融云搭建了一套web及时通信系统,然后之前我的公司也用过环云来实现web及时通信,本人对web及时通信还是非常感兴趣的.私下读了融云和环信的开发文档,然后发现如果注册 ...

  3. [Node.js]29. Level 6: Socket.io: Setting up Socket.io server-side & Client socket.io setup

    Below we've already created an express server, but we want to start building a real-time Q&A mod ...

  4. dotnet调用node.js写的socket服务(websocket/socket/socket.io)

    https://github.com/jstott/socketio4net/tree/develop socket.io服务端node.js,.里面有js写的客户端:http://socket.io ...

  5. Node.js入门:异步IO

    异步IO     在操作系统中,程序运行的空间分为内核空间和用户空间.我们常常提起的异步I/O,其实质是用户空间中的程序不用依赖内核空间中的I/O操作实际完成,即可进行后续任务. 同步IO的并行模式 ...

  6. [Node.js] Level 7. Persisting Data

    Simple Redis Commands Let's start practicing using the redis key-value store from our node applicati ...

  7. [Node.js] Level 3 new. Steam

    File Read Stream Lets use the fs module to read a file and log its contents to the console. Use the  ...

  8. [Node.js] Level 2 new. Event

    Chat Emitter We're going to create a custom chat EventEmitter. Create a new EventEmitter object and ...

  9. [Node.js] Level 5. Express

    Express Routes Let's create an express route that accepts GET requests on'/tweets' and responds by s ...

随机推荐

  1. keil中的memory model

    这两天仿真遇到的怪事真的是一大堆. 还是读写Flash的代码.keil编译OK,但是仿真就是莫名其妙地挂掉出现一些乱七八糟的事情. 后面发现是keil 中的memory model勾选错了,勾选的是l ...

  2. Linux_x86_Pwn溢出漏洞

    基础栈溢出:未开启任何保护的程序 漏洞程序源码 #include <stdio.h>#include <stdlib.h>#include <unistd.h>​v ...

  3. TCP 的那些事儿-1

    TCP是一个巨复杂的协议,因为他要解决很多问题,而这些问题又带出了很多子问题和阴暗面.所以学习TCP本身是个比较痛苦的过程,但对于学习的过程却能让人有很多收获.关于TCP这个协议的细节,我还是推荐你去 ...

  4. BeautifulSoup解析库

    解析库 解析器 使用方法 优势 劣势 Python标准库 BeautifulSoup(html, 'html.parser') 速度适中,容错能力强 老版本python容错能力差 lxml HTML解 ...

  5. 【BZOJ 3136】 3136: [Baltic2013]brunhilda (数论?)

    3136: [Baltic2013]brunhilda Time Limit: 40 Sec  Memory Limit: 128 MBSubmit: 238  Solved: 73[Submit][ ...

  6. [BZOJ 4719] 天天爱跑步

    Link: BZOJ 4719 传送门 Solution: 感觉求LCA又有了新姿势啊:$Tarjan$离线$O(n+m)$ 每次递归返回时将子树和父节点合并,如果询问节点已访问过则LCA就是已合并的 ...

  7. SpringMVC 3.1.1版本下的单元测试WEB-INF路径问题

    假设Spring配置文件为applicationContext.xml 一.Spring配置文件在类路径下面 在Spring的java应用程序中,一般我们的Spring的配置文件都是放在放在类路径下面 ...

  8. 普通主板设置BIOS实现电脑插电自动启动

    说明: 1.为什么要实现这种功能,很多时候在民间都基本用普通PC来做小型服务器,公司的私服等等,而这些普通PC在民用电环境中经常会停电,一停就会导致服务器不能自动来电重启,所以这个功能来点开机是必须的 ...

  9. winform 取消datagridview第一行选中状态

    C# WinForm 取消DataGridView的默认选中Cell 使其不反蓝 http://www.cnblogs.com/freeliver54/archive/2009/02/16/13913 ...

  10. 计蒜之道 初赛 第三场 题解 Manacher o(n)求最长公共回文串 线段树

    腾讯手机地图 腾讯手机地图的定位功能用到了用户手机的多种信号,这当中有的信号的作用范围近.有的信号作用的范围则远一些.有的信号相对于用户在不同的方位强度是不同的,有的则是在不论什么一个方向上信号强度都 ...