M
M
Mikhailo Poberezhny2016-01-26 10:37:03
MongoDB
Mikhailo Poberezhny, 2016-01-26 10:37:03

How to show added comments in real-time?

there is a table with a list of posts and a table with a list of comments to them that are linked by post ID. When adding a new comment, I need to display it immediately. They advised socket.io, but I can’t figure it out in any way, I find examples only with chats, and I can’t attach them to the comments, help with an example or advice. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Pasyuta, 2016-02-04
@as_for_me

Globally, in your case - there is no difference between displaying a comment on a post to everyone on the page and displaying a message in the chat to everyone who is currently in it. Therefore, examples with chats are quite suitable.
And the logic is approximately as follows:
1) On the server, create a socket server that will listen on a certain url:port

var express = require('express');
var app = express();
var io = require('socket.io')(http);
 http = require('http').Server(app);
 http.listen(yourPort, yourUrl, function () {
        console.log('App listening at http://%s:%s', yourUrl, yourPort);
        io.on('connection', function(socket){...}

2) Connect to this url:port on the client
3) On the client, listen to some event from the server. For example, let's call it onCommentAdd
socket.on('onCommentAdd', function(msg) {
        yourFuncToAddCommentInHTMLDOM(msg)
 });

Where in place of msg there will be all the necessary information from the server about the comment
4) On the server, when you have saved to the comment base, call the emit method of your io instance with the necessary parameters. More or less like this
In principle, this is all, if you do everything correctly, then you will receive a new comment on the client.
Hope this helps

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question