Can I send multiple responses via Node.js to the client? - model-view-controller

I'm using Node.js and I want to send back multiple responses to the client. So the client will send an AJAX POST request and get back some data. But the server has to continue to do some processing and when that's done, I want it to send more data back.
I know this is a good candidate for Socket.io, but I haven't really seen an example of how to use socket.io in the context of an MVC framework. Does it go in the controller?

You could use Server Sent Events.
Here's an example:
https://github.com/chovy/nodejs-stream (full source code example)
UI
var source = new EventSource('stream');
source.addEventListener('a_server_sent_event', function(e) {
var data = JSON.parse(e.data);
//do something with data
});
Node
if ( uri == '/stream' ) {
//setup http server response handling and get some data from another service
http.get(options, function(resp){
resp.on('data', function(chunk){
res.write("event: a_server_sent_event\n");
res.write("data: "+chunk.toString()+"\n\n");
});
});
}

Related

How to add data to IndexedDb in service worker which are coming as http response from api

I have a application in codeigniter and angular framework. All its data are coming from api's that are we have created in codeigniter . Now i am trying make this application a pwa . so far,caching of static file and manifes.json are working ,but when it comes to storing those data in IndexedDb and retriving them i am confused how to that.Till now i have find only examples with static json being inserted into IndexedDb ,but i want to know how to store those http response in indexedDb, so that when it goes in offline mode it automatically provide data.Also in every page have more than one http response is coming so it should also provide right data to variables..
If you any part of question than just let me know ,I will try better to explain.
And thank you all in advance.
If the response from api is JSON or some similar sort of data file then you can store in indexDB as string or manipulate as you need.Here's an example of storing JSON as string.
//JSONfile is the response from your api.
var JSONstring = JSON.stringify(JSONfile)
// Storing JSON as string in indexDB
var dbPromise = idb.open('JSON-db', 1, function (upgradeDB) {
var keyValStore = upgradeDB.createObjectStore('JSONs')
keyValStore.put(JSONstring, 'samples')
})
//provide better key name so that you can retrieve it easily from indexDB
Other case if response is some sort of multimedia then you can convert it into blob and then store the blob in indexDB.
return fetch(new Request(prefetchThisUrl, { mode: 'no-cors' }))
.then((resp) => {
resp.blob()
.then((blob) => {
return db.set(prefetchThisUrl, blob);
});
});
You can then get the information from indexDB when required.For a good understanding of storing and retrieving blob from indexDB you can visit this site:https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/
And for providing right data on your page it's not an issue,you just need to make your logic to respond to request from indexDB.Here's how you can do it.
dbPromise.then(function (db) {
var tx = db.transaction('JSONs')
var keyValStore = tx.objectStore('JSONs')
return keyValStore.get('samples')
}).then(function (val) {
var JSONobject = JSON.parse(val)}

Websocket connection. Why are we making a call to ws://echo.websocket.org?

I am writing some websocket code and I have this so far:
window.onload = function() {
// Get references to elements on the page.
var form = document.getElementById('message-form');
var messageField = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');
var socket = new WebSocket('ws://echo.websocket.org');
// Show a connected message when the WebSocket is opened.
socket.onopen = function(event) {
socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.url;
socketStatus.className = 'open';
};
// Handle any errors that occur.
socket.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
form.onsubmit = function(e) {
e.preventDefault();
// Retrieve the message from the textarea.
var message = messageField.value;
// Send the message through the WebSocket.
socket.send(message);
// Add the message to the messages list.
messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message +
'</li>';
// Clear out the message field.
messageField.value = '';
return false;
};
socket.onmessage = function(event) {
var message = event.data;
messagesList.innerHTML += '<li class="received"><span>Received:</span>' +
message + '</li>';
};
closeBtn.onclick = function(e) {
e.preventDefault();
// Close the WebSocket.
socket.close();
return false;
};
socket.onclose = function(event) {
socketStatus.innerHTML = 'Disconnected from WebSocket.';
socketStatus.className = 'closed';
};
};
What is this code doing:
var socket = new WebSocket('ws://echo.websocket.org');
What url is that? When I visit there with my browser it does not exist but it seems to be important as I can't simply jus replace that url with random strings. What does it do? Is Websocket an external API?
I'm looking at the network tab and I see this:
Request URL: ws://echo.websocket.org/
Request Method: GET
Status Code: 101 Web Socket Protocol Handshake
conceptually, what is going on? Why do I need to make a request to an external site to use Websockets?
echo.websocket.org provides a webSocket server that lets you make a webSocket connection to it and then it simply echos back to you anything that you send it. It's there primarily for testing and demo purposes.
The code you show looks like a demo/testing app designed to run in a browser web page for a webSocket connection which you can access something similar here: https://websocket.org/echo.html.
A URL starting with ws:// indicates a connection that intends to use the webSocket protocol.
What is this code doing:
var socket = new WebSocket('ws://echo.websocket.org');
It is making a webSocket connection to a webSocket server at echo.websocket.org.
What url is that?
That is a webSocket URL that indicates the intent to use the webSocket protocol to connect and talk to that host. This is not something you type in the URL bar of a browser. It's something that is used by a programming language (such as Javascript in your browser).
Is Websocket an external API?
It's a protocol that specifies a means of connecting, a security scheme, a packet data format, etc... You could say that the http protocol is to the webSocket protocol as the English language is to Japanese. They are different means of communicating. The specification for the webSocket protocol is here: https://www.rfc-editor.org/rfc/rfc6455.
It's also designed to fit well into the http/browser world and to be friendly with infrastructure that was originally designed for http requests. Just searching for "what is websocket" on Google will turn up all sorts of descriptive articles. The Wikipedia page for webSocket provides a pretty good overview.
There is tons written on the web about what the webSocket protocol is and is useful for so I won't repeat that here. You can see a tutorial on webSocket clients here and a tutorial on webSocket servers here.
In a nutshell, it's designed to be a long lasting, continuous connection (supported in all modern browsers) that allows a client to connect to a server and then maintain a continuous connection for (potentially) a long duration. While that connection is open, data can be easily sent both ways over the webSocket. The primary reason people use it is when they want the server to be able to send data directly to the client in a timely fashion without making the client continuously ask the server over and over again if it has any new data. Once a webSocket connection is established, the server can just "push" data to the client at any time.
I'm looking at the network tab and I see this. Conceptually, what is going on?
Request URL: ws://echo.websocket.org/
Request Method: GET Status Code:
101 Web Socket Protocol Handshake
Those are the first steps of establishing a webSocket connection. You can see a more complete description of how that connection works here: How socket.io works. That post talks about socket.io which is another layer built on top of webSocket, but the underlying protocol is webSocket.
Why do I need to make a request to an external site to use Websockets?
A webSocket's purpose is to connect a client to a server (so data can then be sent between them) so it would only be used when connecting to some server somewhere.

How can I access data sent via AJAX on Node JS server?

I would like to make a simple contact form for my website. I know how to use ajax to send data, but I don't know how to access it on the Node JS server.
If I were to send my data using this code:
var request=new XMLHttpRequest();
request.open("POST","url");
request.send("{value:'10'}");
How can I access my value in the JSON object I pass to the server?
There are a lot of ways to do this.
For example you could create an endpoint on your server e.g. with express http://expressjs.com/. It might look like this
router.post('/your/url', function(req, res, data) {
var value = req.body.value;
// do cool things with value
res.send('cool');
});
You define a post endpoint which will handle your request. Using the request object you can access the JSON object from the request
I used request_.on("data", function(data_){}); to get my data.
If in my client JS I use request.send("my data");
I can access my data by adding a listener to the request_ object in my Node JS server function.
request_.on("data", function(data_){
console.log(data_);// my data
}
I can then slice up my data any way I want to and use it how I see fit. No need for Express.
Here's my client function that is called when the submit button on my contact form is pressed:
function clickSubmit(event_) {
var xmlhttprequest = new XMLHttpRequest();
xmlhttprequest.open("POST", "contact");
xmlhttprequest.send("email=" + html.email.value + "&name=" + html.name.value + "&message=" + html.message.value);
}
And here's my Node JS server function:
function handleRequest(request_, response_) {
switch(request_.url) {
case "/contact":
request_.on("data", function(data_) {
console.log("data: " + data_);// Outputs the string sent by AJAX.
});
break;
}
}

ZeroMQ choose recipient

I'm new to ZeroMQ (and to networking in general), and have a question about using ZeroMQ in a setup where multiple clients connect to a single server. My situation is as follows:
--1 server
--multiple clients
--Clients send messages to server: I've already figured out how to do this part.
--Server sends messages to a specific client: This is the part I'm having trouble with. When certain events get handled on the server, the server will need to send a message to a specific client -- not all clients. In other words, the server will need to be able to choose which client to send a given message to.
Right now, this is my server code:
using (NetMQContext ctx = NetMQContext.Create())
{
using (var server = ctx.CreateResponseSocket())
{
server.Bind(#"tcp://127.0.0.1:5555");
while (true)
{
string fromClientMessage = server.ReceiveString();
Console.WriteLine("From Client: {0}", fromClientMessage);
server.Send("ack"); // There is no overload for the 'Send'
method that takes an IP address as an argument!
}
}
}
I have a feeling that the problem is that my design is wrong, and that the ResponseSocket type isn't meant to be used in the way that I want to use it. Since I'm new to this, any advice is very much appreciated!
when using the Response socket you always replying to the client that sent you the message. So the Request-Response socket types together are just simple request response.
To more complicated scenarios you probably want to use Dealer-Router.
With router the first frame of each message is the routing id (the identity of the client that sent you the message)
so your example with router will look like:
using (NetMQContext ctx = NetMQContext.Create())
{
using (var server = ctx.CreateRouterSocket())
{
server.Bind(#"tcp://127.0.0.1:5555");
while (true)
{
byte[] routingId = server.Receive();
string fromClientMessage = server.ReceiveString();
Console.WriteLine("From Client: {0}", fromClientMessage);
server.SendMore(routingId).Send("ack");
}
}
}
I also suggest to read the zeromq guide, it will probably answer most of your questions.

connected users' list in sails socket

i've currently started using sailsJS with angularJs at frontend alognwith socket for realtime communiction.
Sailsjs gives built-in support to websocket through "sails.io.js".On client side after adding this library this code is added to angular's chat controller.
Client side code
io.socket.get('/chat',{token:token},function(users){
console.log(users);
});
chatController's action on sails side is like this.
Server side code
chat: function (req, res) {
console.log(req.isSocket);
//this gives true when called through client.
})
infact very new to sails so i want suggestion that how to maintain connected user's list because m not using redis as storage purpose.adapter is memory.array is not a good idea because it'll vanish when restart a server.m using sails version of 0.11.0.
thanx in advance.
I'm somewhat new but learning fast, these suggestions should get you there unless someone else responds with greatness...
They changed it in 11 but in 10.5 I use sockets.js in config folder and on connect I store the session data in an array with their socket.
I created a service in APIs/service that contains the array and socket associate function.
For v11 you can't do that exactly the same, but you can make your first 'hello' from the client call a function in a controller that calls the associate function.
A couple tips would be don't let the client just tell you who they are, as in don't just take the username from the params but get it from req.session
(This assumes you have user auth setup)
In my case I have
in api/services/Z.js (putting the file here makes it's functions globally accessible)
var socketList = [];
module.exports = {
associateSocket: function(session, socket) { // send in your username(string) socket(object) id(mongoId) and this will push to the socketlist for lookups
sails.log.debug("associate socket called!",socketList.length)
var iHateYou = socketList
//DEBUG
var sList = socketList
var util = require('util')
if (session.authenticated){
var username = session.user.auth.username
var userId = session.user.id
// sails.log.debug("Z: associating new user!",username,userId,socket)
if (username && socket && userId) {
sList[sList.length]= {
username: session.user.auth.username,
socket: socket,
userId: session.user.id,
};
sails.log.debug('push run!!! currentsocketList length',socketList.length)
} else sails.log("Z.associateSocket called with invalid data", username, userId, authId, socket)
}else{sails.log.warn("Z.associateSocket: a socket attempted to associate itself without being logged in")}
},
}
in my config/sockets.js
onConnect: function(session, socket) {
Z.associateSocket(session,socket)
if (session.user && session.user.auth){
sails.log("config/sockets.js: "+session.user.auth.username+" CONNECT! session:",session)
}else sails.log.warn('connect called on socket without an auth, the client thinks it already has a session, so we need to fix this')
// By default, do nothing.
},
Then you can make add some functions to your services file to do lookups based on username and passwords, remove sockets that are disconnecting and the like (I'm using waterlock for my auth at the moment, although debating the switch back to sails-generate-auth)
Remove your onConnect and dicconnect function from config/sockets.js.

Resources