S
S
skver912015-02-27 20:40:10
PHP
skver91, 2015-02-27 20:40:10

How to send a message to only one user?

Hello. The other day I wanted to make an application that had the ability to exchange messages with users. The essence of this application is that the user registers, he has a profile, and in his profile
you can write an open message to any authorized users. I made all the pages, all messages are sent to the database via ajax, in general, everything is as it should be. Recently started learning nodejs. And I wanted the messages to come in real time. For this, I began to use sockjs. And wrote server.js:

var http = require('http');
var sockjs = require('sockjs');

var clients = {};

// Broadcast to all clients
function broadcast(){
    // iterate through each client in clients object
    for (var client in clients){
        // send the message to that client
        clients[client].write(null);
    }
};

// create sockjs server
var echo = sockjs.createServer();

// on new connection event
echo.on('connection', function(conn) {

    // add this client to clients object
    clients[conn.id] = conn;

    // on receive new data from client event
    conn.on('data', function() {
        broadcast();
        console.log('');
    });

    // on connection close event
    conn.on('close', function() {
        delete clients[conn.id];
    });

});
// Create an http server
var server = http.createServer();

// Integrate SockJS and listen on /echo
echo.installHandlers(server, {prefix:'/echo'});

// Start server
server.listen(3333, '0.0.0.0');

And in an ordinary js file I wrote the following code:
var sock = new SockJS('http://localhost:3333/echo');

// Open the connection

sock.onopen = function() {
    console.log('open');
};

// On connection close

sock.onclose = function() {
    console.log('close');
};


sock.onmessage = function(e) {

    var parentElem = document.getElementById('main');
    var newDiv = document.createElement('div');

    getMessage(getXmlHttp(), document.getElementById('message'), document.querySelector('.login'));

    parentElem.insertBefore(newDiv, parentElem.firstChild);
};

As a result, it turns out that my messages are sent to all authorized users. And it is necessary that messages were sent to the given user. For example, we are at localhost/chat/?user=leha .and we send him a message, but it turns out that we send messages to all users who are on the page localhost/chat/ at the given time. If you have any suggestions, you can send links or hints.
Thanks Skver91

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bumbay, 2015-02-27
@bumbay

Faced exactly this problem.
How to implement message forwarding between two visitors on socket.io?

S
skver91, 2015-03-03
@skver91

https://gist.github.com/Deisss/7941180/download

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question