Book Image

Node.js Blueprints

By : Krasimir Stefanov Tsonev
Book Image

Node.js Blueprints

By: Krasimir Stefanov Tsonev

Overview of this book

Table of Contents (19 chapters)
Node.js Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Implementing user-to-user communication


Our chat is now functioning, but it would be nice if we could send a message to one specific user. Such a feature requires changes in both places: at the frontend and backend. Let's first change the Node.js script.

Changing the server-side code

So far, the users were anonymous in our system. We just passed the received message to all the sockets available. However, to implement a user-to-user conversation, we need to set unique ID for every user. Along with that, we have to keep references to all the created sockets so that we can emit messages to them. This can be done as follows:

var crypto = require('crypto');
var users = [];

We can make use of the crypto module, which is available by default in Node.js to generate the random unique IDs, as follows:

var id = crypto.randomBytes(20).toString('hex');

We should also notify the people in the chat about the available users. Otherwise, they will not be able to pick an appropriate user to chat with. The notification...