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 2014 IDE” and “Express JS Routings with Enide Studio 2014 IDE”.

在阅读文章之前,请仔细阅读我以前的文章: “使用Enide Studio 2014 IDE的Express JS WebApplication”“使用Enide Studio 2014 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编程。

  1. HTML5 WebSocket

    HTML5 WebSocket
  2. Java EE 7 WebSocket API

    Java EE 7 WebSocket API
  3. 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:)

  1. Faster and Two-way Communication

    更快的双向通讯
  2. Cross-Browser Support

    跨浏览器支持
  3. Cross-Platform Support

    跨平台支持
  4. 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 2014 IDE” for more details.)

    使用默认设置“ socketio”创建一个Node.js:Express JS项目(有关更多详细信息,请参阅我之前的文章“ 使用Enide Studio 2014 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 2014 IDE and observe newly added socketio library to our project as shown below:

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

  • Update app.js with the following content:

    使用以下内容更新app.js:
  • app.js

    app.js

    // Required Modules
    var 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');
    
    // Routings
    var index = require('./routes/index');
    var user = require('./routes/users');
    
    // Create Express App
    var app = express();
    app.set('port', process.env.PORT || 3000);
    
    //view engine setup
    app.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

    代码说明

    1. Line No 1-9, importing all required dependency Node JS modules into our application

      1-9行,将所有必需的依赖项Node JS模块导入我们的应用程序
    2. Line No 12-13, importing Routings into our application

      12-13行,将路由导入到我们的应用程序中
    3. Line No 16, Create Express JS Application object

      第16行,创建Express JS Application对象
    4. Line No 17, Set Express WebServer port to listen. This is how we can set our desired port number.

      第17行,将Express WebServer端口设置为侦听。 这是我们可以设置所需端口号的方法。
    5. Line No 20-21, Define our application View Template Engine i.e. JADE

      第20-21行,定义我们的应用程序视图模板引擎,即JADE
    6. Line No 33, Create an HTTP Server

      第33行,创建一个HTTP服务器
    7. Line No 34, Wrap HTTP Server with Socket IO(WebSocket)

      第34行,用套接字IO(WebSocket)包装HTTP服务器
    8. Line No 36-41, io.sockets.on() to open a WebSocket connection between Client and Server.

      第36-41行,io.sockets.on()打开客户端和服务器之间的WebSocket连接。
    9. Line No 47, Export our application.

      第47行,导出我们的应用程序。
  • Update index.jade file with the following content:

    使用以下内容更新index.jade文件:
  • /views/index.jade

    /views/index.jade

    extends layout
    
    block content
      h1= title
      p 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示例。

    翻译自: https://www.journaldev.com/7995/node-expressjs-socket-io-module

    node js 非阻塞io

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值