在 Azure 云服务中使用 Socket.IO 生成 Node.js 聊天应用程序Build a Node.js chat application with Socket.IO on an Azure Cloud Service

Socket.IO 在 node.js 服务器和客户端之间提供实时通信。Socket.IO provides realtime communication between your node.js server and clients. 本教程指导你在 Azure 上托管一个基于 socket.IO 的聊天应用程序。This tutorial walks you through hosting a socket.IO based chat application on Azure. 有关 Socket.IO 的详细信息,请参阅 socket.ioFor more information on Socket.IO, see socket.io.

以下是已完成应用程序的屏幕截图:A screenshot of the completed application is below:

显示托管在 Azure 上的服务的浏览器窗口

先决条件Prerequisites

确保已安装以下产品和版本才能成功完成本文中的示例:Ensure that the following products and versions are installed to successfully complete the example in this article:

创建云服务项目Create a Cloud Service Project

以下步骤创建将托管 Socket.IO 应用程序的云服务项目。The following steps create the cloud service project that will host the Socket.IO application.

  1. 在“开始”菜单或“开始”屏幕中,搜索“Windows PowerShell”。From the Start Menu or Start Screen, search for Windows PowerShell. 最后,右键单击“Windows PowerShell”并选择“以管理员身份运行”。Finally, right-click Windows PowerShell and select Run As Administrator.

    Azure PowerShell 图标

  2. 创建一个名为 c:\node 的目录。Create a directory called c:\node.

    PS C:\> md node
    
  3. 将目录更改为 c:\node 目录Change directories to the c:\node directory

    PS C:\> cd node
    
  4. 输入以下命令,创建一个名为 chatapp 的新解决方案和一个名为 WorkerRole1 的辅助角色:Enter the following commands to create a new solution named chatapp and a worker role named WorkerRole1:

    PS C:\node> New-AzureServiceProject chatapp
    PS C:\Node> Add-AzureNodeWorkerRole
    

    会看到以下响应:You will see the following response:

    new-azureservice 和 add-azurenodeworkerrole cmdlet 的输出

下载聊天示例Download the Chat Example

对于此项目,我们使用 Socket.IO GitHub 存储库中的聊天示例。For this project, we will use the chat example from the Socket.IO GitHub repository. 执行以下步骤下载该示例,并将其添加到先前创建的项目中。Perform the following steps to download the example and add it to the project you previously created.

  1. 使用“克隆” 按钮创建存储库的本地副本。Create a local copy of the repository by using the Clone button. 还可以使用“ZIP”按钮下载项目。You may also use the ZIP button to download the project.

    用于查看 https://github.com/LearnBoost/socket.io/tree/master/examples/chat 的浏览器窗口,其中突出显示 ZIP 下载图标

  2. 浏览本地存储库的目录结构,找到 examples\chat 目录。Navigate the directory structure of the local repository until you arrive at the examples\chat directory. 将此目录的内容复制到先前创建的 C:\node\chatapp\WorkerRole1 目录。Copy the contents of this directory to the C:\node\chatapp\WorkerRole1 directory created earlier.

    资源管理器,显示从存档中解压缩的 examples\chat 目录的内容

    上面屏幕截图中突出显示的项目是从 examples\chat 目录复制的文件The highlighted items in the screenshot above are the files copied from the examples\chat directory

  3. 在 C:\node\chatapp\WorkerRole1 目录中,删除 server.js 文件,然后将 app.js 文件重命名为 server.js。In the C:\node\chatapp\WorkerRole1 directory, delete the server.js file, and then rename the app.js file to server.js. 这会删除前面由 Add-AzureNodeWorkerRole cmdlet 创建的默认 server.js 文件并替换为聊天示例中的应用程序文件。This removes the default server.js file created previously by the Add-AzureNodeWorkerRole cmdlet and replaces it with the application file from the chat example.

修改 Server.js 并安装模块Modify Server.js and Install Modules

在 Azure 模拟器中测试应用程序之前,必须进行一些小改动。Before testing the application in the Azure emulator, we must make some minor modifications. 对 server.js 文件执行以下步骤:Perform the following steps to the server.js file:

  1. 在 Visual Studio 或任何文本编辑器中打开 server.js 文件。Open the server.js file in Visual Studio or any text editor.

  2. 在 server.js 的开头处查找 Module dependencies 节,将包含 sio = require('..//..//lib//socket.io') 的行更改为 sio = require('socket.io'),如下所示:Find the Module dependencies section at the beginning of server.js and change the line containing sio = require('..//..//lib//socket.io') to sio = require('socket.io') as shown below:

    var express = require('express')
      , stylus = require('stylus')
      , nib = require('nib')
    //, sio = require('..//..//lib//socket.io'); //Original
      , sio = require('socket.io');                //Updated
    
     var port = process.env.PORT || 3000;         //Updated
    
  3. 为了确保应用程序侦听正确端口,请在记事本或偏好的编辑器中打开 server.js,然后通过将 3000 替换为 process.env.port,更改以下行,如下所示:To ensure the application listens on the correct port, open server.js in Notepad or your favorite editor, and then change the following line by replacing 3000 with process.env.port as shown below:

    //app.listen(3000, function () {            //Original
    app.listen(process.env.port, function () {  //Updated
      var addr = app.address();
      console.log('   app listening on http://' + addr.address + ':' + addr.port);
    });
    

保存对 server.js 所做更改后,使用以下步骤安装所需的模块,并在 Azure 模拟器中测试应用程序:After saving the changes to server.js, use the following steps to install required modules, and then test the application in the Azure emulator:

  1. 使用 Azure PowerShell,将目录切换到 C:\node\chatapp\WorkerRole1 目录,然后使用以下命令安装此应用程序所需的模块:Using Azure PowerShell, change directories to the C:\node\chatapp\WorkerRole1 directory and use the following command to install the modules required by this application:

    PS C:\node\chatapp\WorkerRole1> npm install
    

    这会安装 package.json 文件中所列的模块。This will install the modules listed in the package.json file. 命令完成后,应该看到类似下面的输出:After the command completes, you should see output similar to the following:

    npm install 命令的输出

  2. 因为此示例最初是 Socket.IO GitHub 存储库的一部分,并通过相对路径直接引用了 Socket.IO 库,而 package.json 文件中未引用 Socket.IO,所以我们必须通过发出以下命令来安装它:Since this example was originally a part of the Socket.IO GitHub repository, and directly referenced the Socket.IO library by relative path, Socket.IO was not referenced in the package.json file, so we must install it by issuing the following command:

    PS C:\node\chatapp\WorkerRole1> npm install socket.io --save
    

测试和部署Test and Deploy

  1. 通过发出以下命令启动模拟器:Launch the emulator by issuing the following command:

    PS C:\node\chatapp\WorkerRole1> Start-AzureEmulator -Launch
    > [!NOTE]
    > If you encounter issues with launching emulator, eg.:
      Start-AzureEmulator : An unexpected failure occurred.  Details: Encountered an unexpected error The communication object,  System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.
    
      reinstall AzureAuthoringTools v 2.7.1 and AzureComputeEmulator v 2.7 - make sure that version matches.
    >
    >
    
  2. 打开浏览器并导航到 http://127.0.0.1Open a browser and navigate to http://127.0.0.1.

  3. 浏览器窗口打开后,输入昵称,并按 Enter。When the browser window opens, enter a nickname and then hit enter. 这样,就可以用特定昵称发布消息。This will allow you to post messages as a specific nickname. 要测试多用户功能,请使用同一 URL 打开另外的浏览器窗口但输入不同的昵称。To test multi-user functionality, open additional browser windows using the same URL and enter different nicknames.

    显示用户 1 和用户 2 聊天消息的两个浏览器窗口

  4. 测试应用程序之后,发出以下命令停止模拟器:After testing the application, stop the emulator by issuing the following command:

    PS C:\node\chatapp\WorkerRole1> Stop-AzureEmulator
    
  5. 要将应用程序部署到 Azure,请使用 Publish-AzureServiceProject cmdlet。To deploy the application to Azure, use the Publish-AzureServiceProject cmdlet. 例如:For example:

    PS C:\node\chatapp\WorkerRole1> Publish-AzureServiceProject -ServiceName mychatapp -Location "China East" -Launch
    

    重要

    确保使用唯一名称,否则发布过程会失败。Be sure to use a unique name, otherwise the publish process will fail. 部署完成后,会打开浏览器并导航到已部署的服务。After the deployment has completed, the browser will open and navigate to the deployed service.

    如果收到错误消息,指出导入的发布配置文件中不存在提供的订阅名称,则必须先为用户的订阅下载和导入发布配置文件,再部署到 Azure。If you receive an error stating that the provided subscription name doesn't exist in the imported publish profile, you must download and import the publishing profile for your subscription before deploying to Azure. 请参阅生成 Node.js 应用程序并将其部署到 Azure 云服务中的“将应用程序部署到 Azure”部分See the Deploying the Application to Azure section of Build and deploy a Node.js application to an Azure Cloud Service

    显示托管在 Azure 上的服务的浏览器窗口

    备注

    如果收到错误消息,指出导入的发布配置文件中不存在提供的订阅名称,则必须先为用户的订阅下载和导入发布配置文件,再部署到 Azure。If you receive an error stating that the provided subscription name doesn't exist in the imported publish profile, you must download and import the publishing profile for your subscription before deploying to Azure. 请参阅生成 Node.js 应用程序并将其部署到 Azure 云服务中的“将应用程序部署到 Azure”部分See the Deploying the Application to Azure section of Build and deploy a Node.js application to an Azure Cloud Service

应用程序现在即可在 Azure 上运行,并可使用 Socket.IO 在不同客户端之间中继聊天消息。Your application is now running on Azure, and can relay chat messages between different clients using Socket.IO.

备注

为简单起见,此示例仅限于连接到同一实例的用户之间的聊天。For simplicity, this sample is limited to chatting between users connected to the same instance. 这意味着如果云服务创建两个辅助角色实例,用户只能够与连接到同一辅助角色实例的其他用户聊天。This means that if the cloud service creates two worker role instances, users will only be able to chat with others connected to the same worker role instance. 要缩放应用程序以使用多个角色实例,可以使用类似于服务总线的技术在实例之间共享 Socket.IO 存储状态。To scale the application to work with multiple role instances, you could use a technology like Service Bus to share the Socket.IO store state across instances. 有关示例,请参阅 Azure SDK for Node.js GitHub 存储库中的服务总线队列和主题使用示例。For examples, see the Service Bus Queues and Topics usage samples in the Azure SDK for Node.js GitHub repository.

后续步骤Next steps

在本教程中,已了解如何创建托管于 Azure 云服务中的基本聊天应用程序。In this tutorial you learned how to create a basic chat application hosted in an Azure Cloud Service. 若要了解如何在 Azure 网站中托管此应用程序,请参阅 在 Azure 网站中使用 Socket.IO 生成 Node.js 聊天应用程序To learn how to host this application in an Azure Website, see Build a Node.js Chat Application with Socket.IO on an Azure Web Site.

有关详细信息,另请参阅 Node.js 开发人员中心For more information, see also the Node.js Developer Center.