2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > node js 非阻塞io_Node Express JS:套接字IO模块示例

node js 非阻塞io_Node Express JS:套接字IO模块示例

时间:2019-03-07 07:13:42

相关推荐

node js 非阻塞io_Node Express JS:套接字IO模块示例

node js 非阻塞io

Before reading post, please go through my previous posts: “Express JS WebApplication with Enide Studio IDE” and “Express JS Routings with Enide Studio IDE”.

在阅读文章之前,请仔细阅读我以前的文章: “使用Enide Studio IDE的Express JS WebApplication”和“使用Enide Studio IDE的Express JS路由” 。

Socket IO简介 (Introduction to Socket IO)

Node JS: Socket IO Module is used to develop Real-time Client-Server Communication applications. It internally uses “WebSocket” Programming model to provide real-time two-way communication between Client and Server.

节点JS:套接字IO模块用于开发实时客户端-服务器通信应用程序。 它在内部使用“ WebSocket”编程模型在客户端和服务器之间提供实时双向通信。

We can observe that the following Technologies offer WebSocket Programming to implement this kind of applications.

我们可以观察到以下技术为实现此类应用程序提供了WebSocket编程。

HTML5 WebSocketHTML5 WebSocket Java EE 7 WebSocket APIJava EE 7 WebSocket API Node JS:Socket IO Module节点JS:Socket IO模块

传统HTTP和WebSocket方法之间的区别 (Difference between Traditional HTTP and WebSocket Approaches)

Traditional HTTP Approach:

We have our old and Traditional HTTP Request-Response Stateless Approach to provide Communication between Client and Server. But it follows “Pushing” model that means when client sends a request to Server, Server pushes the response to the Clients.

传统的HTTP方法:

我们有旧的和传统的HTTP请求-响应无状态方法来提供客户端和服务器之间的通信。 但是它遵循“推送”模型,这意味着当客户端向服务器发送请求时,服务器会将响应推送到客户端。

WebSocket Approach:

We can use WebSocket Approach too to provide Communication between Client and Server. However unlike Traditional HTTP Request-Response Stateless Approach, WebSocket Approach provides Communication between Client and Server by using “Pulling” model that means Server always pulls data to Clients. That’s why is is more efficient and faster approach to provide Client-Server Communication.

WebSocket方法:

我们也可以使用WebSocket方法来提供客户端和服务器之间的通信。 但是,与传统的HTTP请求-响应无状态方法不同,WebSocket方法通过使用“拉”模型在客户端和服务器之间提供通信,这意味着服务器始终将数据拉到客户端。 这就是为什么提供客户端-服务器通信的更有效,更快捷的方法。

Socket IO(WebSocket)编程的优点: (Advantages of Socket IO(WebSocket) Programming:)

Faster and Two-way Communication更快的双向通讯 Cross-Browser Support跨浏览器支持 Cross-Platform Support跨平台支持 Platform independent web framework独立于平台的Web框架

套接字IO设置 (Socket IO Setup)

Unlike some Node JS Default Modules like “npm”,”http”,”events” come with Node JS Platform basic installation (No need of separate steps to install these modules), Socket.IO does not come with as Node JS Default modules. We need to install it manually.

与某些节点JS默认模块(例如“ npm”,“ http”,“事件”)随Node JS Platform基本安装(不需要单独的步骤来安装这些模块)一起提供时,Socket.IO并不随Node JS Default模块一起提供。 我们需要手动安装。

We have already discussed on “How to install a Node JS Module” using “node install” command. If you are not familiar about this command, please go through my previous post : “NPM install update and uninstall example”

我们已经使用“ node install”命令讨论了“如何安装Node JS模块”。 如果您不熟悉此命令,请阅读我以前的文章:“ NPM安装更新和卸载示例”

To install Socket.IO globally

Before staring Express JS Development, first and fore most step We need to do is use “npm install” command to install Express JS module

全局安装Socket.IO

在开始Express JS开发之前,首先要做的第一步是使用“ npm install”命令安装Express JS模块。

npm install -g socket.io

Here “socket.io” means Socket IO Module and “-g” means install Socket.io Module globally.

这里的“ socket.io”表示套接字IO模块,“-g”表示全局安装Socket.io模块。

To verify installation

验证安装

After Socket IO Module installation is done, we need to check whether this module is installed successfully or not. If it is installed successfully, we can find a new folder at

C:\Users\[Windows_USerName]\AppData\Roaming\npm\node_modules\socket.io as shown below:

在完成Socket IO Module的安装后,我们需要检查该模块是否已成功安装。 如果安装成功,我们可以在以下位置找到一个新文件夹

C:\ Users \ [Windows_USerName] \ AppData \ Roaming \ npm \ node_modules \ socket.io,如下所示:

套接字IO示例 (Socket IO Example)

Create a Node.js:Express JS Project with default settings: “socketio” (Please refer my previous post “Express JS WebApplication with Enide Studio IDE” for more details.)使用默认设置“ socketio”创建一个Node.js:Express JS项目(有关更多详细信息,请参阅我之前的文章“ 使用Enide Studio IDE的Express JS WebApplication ”)。 Update “package.json” file with “socket.io” module dependency.使用“ socket.io”模块依赖项更新“ package.json”文件。

Default package.json

默认package.json

{"name": "socketio","version": "0.0.0","private": true,"scripts": {"start": "node ./bin/www"},"dependencies": {"body-parser": "~1.12.4","cookie-parser": "~1.3.5","debug": "~2.2.0","express": "~4.12.4","jade": "~1.9.2","morgan": "~1.5.3","serve-favicon": "~2.2.1"}}

Updated package.json

更新了package.json

{"name": "socketio","version": "0.0.0","private": true,"scripts": {"start": "node ./bin/www"},"dependencies": {"body-parser": "~1.12.4","cookie-parser": "~1.3.5","debug": "~2.2.0","express": "~4.12.4","jade": "~1.9.2","morgan": "~1.5.3","serve-favicon": "~2.2.1","socket.io": "~1.3.5"}}

Observe default “node_modules” folder观察默认的“ node_modules”文件夹

If we observe our project now, it contains all default Express JS Module libraries as shown below:

如果我们现在观察我们的项目,它包含所有默认的Express JS Module库,如下所示:

Update “node_modules” with “socket.io” library.使用“ socket.io”库更新“ node_modules”。

In order to use Socket IO module library, we need to execute the following command at our project root directory:

为了使用Socket IO模块库,我们需要在项目根目录中执行以下命令:

npm install --save socket.io

Here “–save” option means retrieve “socket.io” library from our Local repository and add this to our project. This is something similar to adding JAR files to our Java Project.

这里的“ -save”选项表示从本地存储库中检索“ socket.io”库,并将其添加到我们的项目中。 这类似于将JAR文件添加到我们的Java项目中。

Open command prompt at our project root directory and execute above command:

在我们的项目根目录中打开命令提示符,然后执行以上命令:

NOTE:-Please ignore those errors or warnings.

注意:-请忽略这些错误或警告。

Now refresh your “socketio” project in Enide IDE Studio IDE and observe newly added socketio library to our project as shown below:

现在,在Enide IDE Studio IDE中刷新您的“ socketio”项目,并观察到新添加的socketio库到我们的项目中,如下所示:

Update app.js with the following content:使用以下内容更新app.js:

app.js

app.js

// Required Modulesvar express = require('express');var path = require('path');var http = require('http');var favicon = require('serve-favicon');var logger = require('morgan');var cookieParser = require('cookie-parser');var bodyParser = require('body-parser');var io = require('socket.io');// Routingsvar index = require('./routes/index');var user = require('./routes/users');// Create Express Appvar app = express();app.set('port', process.env.PORT || 3000);//view engine setupapp.set('views', path.join(__dirname, 'views'));app.set('view engine', 'jade');app.use(logger('dev'));app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, 'public')));app.use('/', index);app.use('/users', user);var server = http.createServer(app);io.listen(server);io.sockets.on('connection', function (socket) {socket.on('messageChange', function (data) {console.log(data);socket.emit('receive', data.message.split('').reverse().join('') );});});server.listen(app.get('port'), function(){console.log('Express server listening on port ' + app.get('port'));});module.exports = app;

Code Explanation

代码说明

Line No 1-9, importing all required dependency Node JS modules into our application1-9行,将所有必需的依赖项Node JS模块导入我们的应用程序 Line No 12-13, importing Routings into our application12-13行,将路由导入到我们的应用程序中 Line No 16, Create Express JS Application object第16行,创建Express JS Application对象 Line No 17, Set Express WebServer port to listen. This is how we can set our desired port number.第17行,将Express WebServer端口设置为侦听。 这是我们可以设置所需端口号的方法。 Line No 20-21, Define our application View Template Engine i.e. JADE第20-21行,定义我们的应用程序视图模板引擎,即JADE Line No 33, Create an HTTP Server第33行,创建一个HTTP服务器 Line No 34, Wrap HTTP Server with Socket IO(WebSocket)第34行,用套接字IO(WebSocket)包装HTTP服务器 Line No 36-41, io.sockets.on() to open a WebSocket connection between Client and Server.第36-41行,io.sockets.on()打开客户端和服务器之间的WebSocket连接。 Line No 47, Export our application.第47行,导出我们的应用程序。 Update index.jade file with the following content:使用以下内容更新index.jade文件:

/views/index.jade

/views/index.jade

extends layoutblock contenth1= titlep Welcome to span.received-message #{example}input(type='text', class='message', onkeyup='send(this)')script(src="/socket.io/index.js")script.var socket = io.connect('https://localhost');socket.on('receive', function (message) {console.log('received %s', message);document.querySelector('.received-message').innerText = message;});function send(input) {console.log(input.value)var value = input.value;console.log('Sending Client Message: %s to Server', value);socket.emit('messageChange', {message: value});}

Update index.js file with the following content:使用以下内容更新index.js文件:

/routes/index.js

/routes/index.js

var express = require('express');var router = express.Router();/* GET home page. */router.get('/', function(req, res, next) {res.render('index', { example: 'Node Express JS: Socket.IO Module',title: 'Socket.IO Module' });});module.exports = router;

Final project structure looks like this:最终的项目结构如下所示:

执行套接字IO示例 (Execute Socket IO Example)

Open command prompt at our project root directory and execute below command:在项目根目录中打开命令提示符,然后执行以下命令:

npm start

Run Socket IO Example and observe the output运行Socket IO Example并观察输出

Access application using this URL: https://localhost:3000/

使用以下URL访问应用程序:https:// localhost:3000 /

To see WebSocket power Internally, please use Mouse Right Click and Select “Inspect Element” as shown below:

要在内部查看WebSocket的电源,请使用鼠标右键单击并选择“检查元素”,如下所示:

Select “Console” tab. Type some text in “Textbox” and observe the Console output as shown below:

选择“控制台”选项卡。 在“文本框”中输入一些文本,并观察控制台输出,如下所示:

Our application sends each and every character immediately to server. That’s the beauty of WebSocket Programming.

我们的应用程序将每个字符立即发送到服务器。 这就是WebSocket编程的美。

That’s it about Express: Socket IO Module Example.

关于Express:套接字IO模块示例。

In my next post, I will give you another Socket IO Module example without using Express JS WebFramework.

在我的下一篇文章中,我将给您另一个不使用Express JS WebFramework的Socket IO Module示例。

翻译自: /7995/node-expressjs-socket-io-module

node js 非阻塞io

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。