Answer the question
In order to leave comments, you need to log in
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');
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);
};
Answer the question
In order to leave comments, you need to log in
Faced exactly this problem.
How to implement message forwarding between two visitors on socket.io?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question