メイン コンテンツにスキップ

 Subscribe

With Azure Mobile Service .NET backend you can do realtime communication using SignalR however such an option was not available for our node backend customers. With the latest update of Azure Mobile Service node backend, we’ve made it easy for you to hookup socket.io with your Mobile Service.

Installation

First of all clone your Mobile Service git repository locally like so:

C:> git clone 

Then change your directory to ‘service’ folder and install ‘socket.io’ module

cd nodetestappservice
npm install socket.io --save

Note: To avoid pushing the node_modules folder in your remote repository, you have to add the .gitignore file. See Support for package.json in Azure Mobile Services for details.

Now change your directory to ‘extensions’ folder and create a file called ‘startup.js’ with following contents:

var path = require('path');

exports.startup = function (context, done) {
	var io = require('socket.io')(context.app.server);
	io.on('connection', function(socket){
	  socket.on('chat message', function(msg){
		io.emit('chat message', msg);
	  });
	});	

       context.app.get('/public/chat.html', function(req, res) {
		res.sendfile(path.resolve(__dirname, '../public/chat.html'));
	});	
	done();
}

In the snippet above we configured socket.io and added a route to host our chat app.

Chat app

Create a new file ‘chat.html’ and put it in a new folder called ‘public’ inside the ‘service’ folder with following html:



  
    Socket.IO chat
    
  
  
    

    Finally commit all your changes and push them up to your Mobile Service using add, commit and push commands of git.

    Then visit and you’ll see a page that shows you a text box and a button at the bottom. Open two instances of this page in the browser. Type a message and press enter. You’ll see the message in the other window too.

    Scale out

    The above sample works only when you have a single instance of your Mobile Service. If you have multiple instances then you’ll need to use redis as a backing store for your realtime communication along with socket.io. For that you can install the socket.io-redis node module from npm

    https://www.npmjs.org/package/socket.io-redis

    And you can configure it to work against your redis instance in Azure. See the following article for details:

    https://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/

    • Explore

       

      Let us know what you think of Azure and what you would like to see in the future.

       

      Provide feedback

    • Build your cloud computing and Azure skills with free courses by Microsoft Learn.

       

      Explore Azure learning


    Join the conversation