With the Net Stream Object with TCP works great (as presetend in the node.js introduction video), but how should I do this in HTTP?
Is there a way to access sockets/clients within an http.createServer()
? Or what's the method to do it? I tried to figure out the solution from the official node chat demos souce code, but I don' really understand.
I understand the client side js, but what's happening after I(as a client) send a message trough AJAX, to the server side js? How can I send to the other clients who's on the server too?
Please note that I wan't to learn the logic of the process, so I don't want to use socket.io or any other frameworks, libraries, modules.
Thanks very much for any help!
If you want to know the basic principles of long polling then try to look at this article. I summarized there certain parts of my own long poll server, how I implemented them and the article also contains links to other resources. It should give you at least the bigger picture of how long polling works.
If you want to learn the logic in order to have some coding fun with node.js, and not to use existing solutions, then I would recommend to go step by step from the most simple and basic implementation to more complex stuff. Don't try to build the entire thing from the first shot because it's one of the most surest way how to fail.
Ideally you just use
WebSockets
but the alternative is ajax long polling.You can use a technique known as long polling to do the chat. This means you make an (ajax) request to the server and the server keeps hold of this request until it has some data left to send.
So the clients ends up periodically polling the server, if the server has no new messsages, it just keeps hold of your request. If it has a message it sends it back to the client and the client will poll the server again.
[[Pseudo Code]]
// Client.js
// server.js
A better push technology would be Server-side events. See an example of it here. This does require browser support though (Chrome and opera I think).
One way of doing it involves clients "subscribing" to a channel that acts as a distributor for messages. Once subscribed, a client then receives a copy of each message sent to the channel.
Many node chat services rely on redis' pubsub feature to handle this distribution of messages from one to any number of clients. If you wanted to "roll your own", understanding how redis solves this problem would be a great start.