0

I am creating customer service chat application that get data from client website to node.js server then send this data to agent and the agent reply to the client..

Server code:

var ws = require("nodejs-websocket");
var clients = [];
var server = ws.createServer(function(conn){
    console.log("New Connection");

    //on text function
    conn.on("text", function(str){

        var object = JSON.parse(str);
        conn.sendText("Message send : " + object);
        console.log("User ID: " + object.id);


        clients.push(object.id);

        var unique=clients.filter(function(itm,i,a){
            return i==a.indexOf(itm);
        });
        /*
        conn.on('message', function("test") {
            console.log('message sent to userOne:', message);
            unique[0].send("Message: " + message);
        });
        */
        console.log("Number of connected users : " + unique.length);

        //closing the connection
        conn.on("close", function(){
            console.log("connection closed");

        });
    });



}).listen(process.env.PORT, process.env.IP);

Everything works perfectly and I have each client ID but the I want to reply with a message to that client ID..

What I have tried:

I have tried to reply to the client using conn.send("message", callBackFunction) but it send to all not with a specified user ID.

1 Answer 1

1

Disclaimer: co-founder of Ably - simply better realtime

You have two problems there I suspect. Firstly, if you ever need to scale to more than one server you've got problems as you will need to figure out how to pass messages between servers. Secondly, you have no way of maintaining state between disconnections which will happen as part of normal behaviour for clients.

The industry typically approaches this type of problem using the concept of channels as it scales, it decouples the publisher from the subscriber, and it's quite a simple concept to work with. For example, if you had a channel called "client:1" and you published to that channel, and your subscriber was listening on that channel, then they would receive the message. You can find out more about how we have designed our realtime service around channels, I would suggest you do consider that pattern in your system.

Matt, co-founder, Ably

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please tell me the solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.