Connection stream - javascript

Is there another way to create a connection stream between a loaded page (client) and the server without using repeated AJAX calls, like every half second? I think of something that will make the client listening until the server gives a response (which can take a few seconds to arrive).
Thank you for your answers.

I would like to recommd you Phil Leggetter's Guide to Real-time technologies - because that is what you are looking for.
You will need one of the html5 introduced connection aspects: WebSockets, Server-Sent Events or even WebRTC DataChannel could be possible if you have a peer-to-peer use case.
In reference to the above link, its always about your server setup and your use case - that in mind some commonly used technologies would be: Pusher, Firebase, Socket.io, Ratchet, etc.
Update
Server-sent-events do have more server-side compatibilitly, technically it is more like optimized HTTP streaming, you can read more details in the spec and on caniuse.
If you need a constant bidirectional connection and better client side support you better go with WebSockets. But you will need to set up a compatible server or use an external service like Pusher or Firebase.

Related

Is there a browser-based Websocket listener implementation?

I am interested to know if anyone has built a javascript websocket listener for a browser. Basically the server side of a websocket that runs in a client. This would allow messages to be sent to the client directly. Why? Because instead of having a Node.js, python, java, etc, server process sitting on or near the client/browser, I can just use a thread in the browser as a listening server thread. I don't think that any browsers support this currently.
I've run across answers like this: https://news.ycombinator.com/item?id=2316132
Just curious if anyone has done this. I believe that the current Websockets spec does not support listeners on the browser. It would make the deployment of various peer-to-peer applications a bit easier to deploy.
WebRTC allows for peer-to-peer connections to be made between browsers.
You would still need a server in order for individual users to discover each other but then they could connect directly to each other rather than having to pass all their traffic via a central server.
The idea.
You can use a simple echo server written in any language. Your script can send the data to the server then get it back, handle it on the same page with different functions/classes emulating the real server.
An example: http://www.websocket.org/echo.html
Then, you can think about different formats of packets to/from server to diffirentiate them inside one script.

Using AJAX vs. socket.io socket messages

I am writing a chat application with friend request capabilities, and currently using socket.io events to send/receive messages between users.
I'm conflicted on when to use AJAX and when to use sockets in the event that I have access to the socket. i.e.
$.ajax({url:'friendAdd'}) vs socket.emit('friendAdd');
for all my friend request logic.
Would it be better to stay consistent throughout the application and use sockets for all other requests, or are there reasons that using AJAX would be more optimal?
I'd say it really depends on a request by request basis what you're doing. Once you have a socket.io connection established, it is technically a bit more efficient to just use it for everything since the connection is already established on both ends so all you have to do is send a message packet.
But, some requests from client to server (depending upon what they are) may benefit from some of the HTTP infrastructure that is already built into your HTTP framework on the server (like Express). For example, if you were uploading a file, you could do it over the socket.io connection, but there's a lot of code already built to do that over HTTP that you could just use and that may not already exist for doing that type of request over socket.io. Or, if you are using various Express middleware for sessions, cookies, authentication, routing, etc... it may be much easier to take advantage of all that existing infrastructure and modules in the http world rather than try to reimplement for socket.io messages.
Personally, I would tend to keep the socket.io traffic to chat related traffic only and obviously anything that must be server push and then use regular Ajax calls for other functions that aren't directly chat. But, there's no exact answer there, it really depends upon what you think is the cleanest architecture and best encapsulation of functionality.
FYI, some interesting discussion (and other references) around this topic in this other answer: Ajax vs Socket.io

Node.js chat without Socket.IO

I just started learning Node.js and as I was learning about the fs.watchFile() method, I was wondering if a chat website could be efficiently built with it (and fs.writeFile()), against for example Socket.IO which is stable, but I believe not 100% stable (several fallbacks, including flash).
Using fs.watchFile could perhaps also be used to keep histories of the chats quite simply (as JSON would be used on the spot).
The chat files could be formatted in JSON in such a way that only the last chatter's message is brought up to the DOM (or whatever to make it efficient to 'fetch' messages when the file gets updated).
I haven't tried it yet as I still need to learn more about Node, and even more to be able to compare it with Socket.IO, but what's your opinion about it? Could it be an efficient/stable way of doing chats?
fs.watchFile() can be used to watch changes to the file in the local filesystem (on the server). This will not solve your need to update all clients chat messages in their browsers. You'll still need web sockets, AJAX or Flash for that (or socket.io, which handles all of those).
What you could typically do in the client is to try to use Web Sockets. If browser does not support them, try to use XMLHttpRequest. If that fails, fallback to Flash. It's a lot of programming to do, and it has to be handled by node.js server as well. Socket.io does that for you.
Also, socket.io is pretty stable. Fallback to Flash is not due to it's instability but due to lack of browser support for better solutions (like Web Sockets).
Storing chat files in flatfile JSON is not a good idea, because if you are going to manipulating the files, you would have to parse and serialize entire JSON objects, which would become very slow as the size of the JSON object increased. The watch methods for the filesystem module also don't work on all operating systems.
You also can't compare Node.js to Socket.IO because they are entirely different things. Socket.IO is a Node module for realtime transport between the browser and the server. What you need is dependent on what you're doing. If you need chat history, then you should be using a database such as MongoDB or MySQL. Watching files for changes is not an efficient way and you should just send messages as they received.
In conclusion no, using fs.watchFile() and fs.writeFile() is a very bad idea, because race conditions would occur due to concurrent file writes, besides that fs.watchFile() uses polling to check if a file has changed. You should instead use Socket.IO and push messages to other clients / store them in a database as they are received.
You can use long pooling method using javascript setTimeout and setInterval
long pooling
basically long pooling working on Ajax reqest and server responce time.
server will respond after a certain time (like after 50 seconds ) if there is not notification or message else it will respond with data and from client side when client gets response client javascript makes another request for new update and wait till response this process is endless until server is running

Advice on which technology to use for real time notifications

I have X amount of activity sensors connected to a server that inserts data to a database everytime a sensor is triggered. What I'm trying to do is create a web interface with a blue print of the facility (svg) and whenever a sensor is triggered, besides the db insert, I want it to show some sort of alert in my blue print. For that I need to keep an open connection to the server I think.
I was thinking of using web sockets, but it might be overkill since I only need to retrieve data from the server. But running an ajax call every second doesn't sound very efficient either. Are there any other alternatives?
Thank you
Some potential choices include:
WebSocket
Adobe® Flash® Socket
AJAX long polling
AJAX multipart streaming
Forever Iframe
JSONP Polling
Which actual transport you end up using will depend on the your requirements for browser support and what technology you are using on the server to handle these requests. The transport choice may also depend on your network topology - what types of load balancers you need to integrate with, proxies, etc.
There are many libraries available on both the client and server sides, many of which support more than one of these transports.
For example (not an exhaustive list):
socket.io for nodejs
WebSocket
Adobe® Flash® Socket
AJAX long polling
AJAX multipart streaming
Forever Iframe
JSONP Polling
SignalR for an asp/.net backend
WebSockets
Server-Sent Events
ForeverFrame
Long Polling
Atmosphere for a java backend
WebSockets
Server Side Events (SSE)
Long-Polling
Forever frame
JSONP
IMO - Websockets is NOT overkill for this type of problem and would lend itself nicely to this type of application.
Without specifically discussing frameworks or knowing what is running in the backend of your server(s), we have a few options to consider for the frontend:
Websockets
Websockets are designed for bidirectional communication, although it is kind of shocking how many users are surfing the web in a browser that doesn't support websockets. I always recommend a fallback for this, such as the other methods listed below.
SSE
SSE is an HTML5 spec and is still shaky at best. Try scrolling on a page while when an SSE event fires... It may be a little easier on the backend, put it sometimes hangs on the client side since it runs inside the same thread that the DOM is running in.
Long Polling
Keeps your connection open. It doesn't scale well with PHP, but performs swimmingly with Python+Twisted on the backend, or Node.Js
Good Old Ajax
Keep your requests small, and you still have a scalable solution. Yes, a full GET request is the most expensive, but is supported in just about every browser rolled out the past ten years. It is also worth noting that GET requests are easy to scale horizontally with more hardware.
In a perfect world:
You would break up your application into a few components, operating behind a reverse proxy such as Nginx. Then use Node.Js + Socket.IO handle the realtime aspects of your app.
Another option would be to use small Ajax requests, and offer websocket support for the browsers that support it. This is advice specifically for PHP in the backend.
WebSocket is certainly not overkill. On the contrary. With websockets, you have a bi-directional communication channel; this means, that the server can initiate communication whenever it seems fit (e.g. when sensor data changes).
In a previous project, I have used node.js together with socket.io, to monitor 50+ sensors. Data was updated in real-time in a browser. The data was visualized using smoothie.js.
Whenever a sensor value was updated, it was communicated to the browser. Some sensors only updated once a minute, others once a second, ...
Polling would have been overkill, because it would retrieve all data for all sensors, even from those that were not updated yet.
I had a similar problem and did a lot of research on this. As I understand it, there are three main options:
Short polling: Have an endpoint that your javascript client pings every second. This is the worst option, because the pings add latency up to one second to your communication, and depending on how you implement, the endpoint could query the database every second, adding unnecessary overhead.
Long polling: Have an endpoint that your javascript client pings that holds the connection until a) the event occurs or b) the connection times out. If the endpoint returns a response, the client gets the event information. If the endpoint does not return a response, no event has occurred, and the client sends a new request. This is a good option because the events can immediately trigger the response to the client, assuming you have an asynchronous interprocess communication layer (like 0MQ) to send the message without any sort of polling.
Websocket: Have your javascript client connect to a websocket server, which will send a message to your client immediately upon the event trigger.
I think a websocket is your best option, because it accommodates immediate communication of the event without all the request/response overhead. And most importantly, this is exactly what websockets are designed to do! As such, you will probably have to write the least amount of custom code with this solution.
There are two great commercial services that might work for you.
Firebase - a javascript hierarchical database and realtime
messaging/ synchronization platform, uses websockets and has other fallbacks
PubNub - a real time message passing and queue system, uses websockets

callback javascript

I write a browser game (php, javascript) and I do not know how to make a callback. necessary that the server itself
found a client and call the function (only had one)
Don't write a browsergame if you don't know the basics! Browsergames are way too complex to learn programming.
If you want to make the server notify a client about something you will need to keep a connection open (search keywords: COMET, long polling) as you cannot initiate connections from the server to clients.
For this I can suggest you using Firebase. It is a API that let you to add cloud Data management that your user clients do. You can use that communication to search for client.
If I understand your question, what you need is a socket. Since you're using PHP and Javascript, a WebSocket might be just what you're looking for. With WebSockets, the connection between the client and the server is persisted, so the server can just push data/messages to any or all of the clients connected to it at any point in time. Likewise, the any client connected to the server can push messages/data up to the server.
Here's a video that describes how it works a bit https://www.youtube.com/watch?v=oJxWhmt5m-o

Categories

Resources