Question

I know how to send a request between a client and Node server and respond to the client's request, like this:

Node:

function listen() {
    app.use(express.bodyParser());

    app.post('/login', function (req, res) {

        var username = req.body.username;
        var password = req.body.password;

        console.log('User ' + username + ' is attempting login...');
        validate(username, password, function (err, result) {
            if (err) loginFail(req, res, err);
            else loginSucceed(req, res, result);
        });
    });

    app.listen(8080, function () {
        console.log('Server running at http://127.0.0.1:8080/');
    });
}

Client:

function sendLogin() {

    popLogCreds(creds);

    if (valLoginCreds(creds)) {

        var loginCredentials = {
            "username": creds.username,
                "password": creds.password
        };

        request = $.ajax({
            url: "http://127.0.0.1:8080/login",
            type: "POST",
            crossDomain: true,
            data: loginCredentials,
            dataType: "json"
        });

        request.always(function (data) {

            //process response

        });

    }
}

But I haven't been successful in figuring out how to keep a connection between client and server open for the length of the client's experience.

For example, if I wanted to have the server push data to the client each time something new happened.

Can it be done in native Node, or must I use Socket.io for that?

Was it helpful?

Solution

I think you have to use Socket.io (or something it looks like). The server can't send information to the client (without socket).

If you don't want to use socket.io, you can do a setInterval and call a route from your server in order to know if you have new data available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top