Maintaining Connection using WebSockets - javascript

I have a JavaScript/html web socket client. It receives images from my server quite frequently. I am hosting my web socket server in a C# console application.
The longest my client has to wait for an image is 10 seconds.
Should I also be sending 'keep-alive' packets from my client (JavaScript) to my Server or is the fact that it receives regular data packets from my server enough?
Thanks

You can send ping messages from the server, and the client will answer with a pong message. It is part of the WebSocket protocol, not sure if your server implementation supports it. However, from the client you have no way to know if you got a ping message in while, so the client may be let hanging there.
Or you can do it at application level using your own messages. Basically create a "ping" message in JSON and send it regularly from the client to the server, then if you do not get a response in X time, reconnect.
If you don´t, the only problem is that the connection maybe half-open, and your client may be hanging there waiting for a image that will never come.
Cheers.

Related

Sending JSON to all online clients without them making a request. [NodeJS]

I'm building a website, and one of the features is a public chat that anyone online can use. When a message is entered it is sent to the server and then saved to a SQL database. How could I relay this information to all the online clients without them making a request to the server? I've thought about having all clients make a request to the server every 500ms or so but I feel that would be incredibly inefficient. Any suggestions?
What you're looking for is typically called "server push" where the server can unilaterally send data to the client without the client having to "poll" or repeatedly ask for new info.
The two general technologies for server push these days are webSockets and server-sent events (SSE). In both cases, the client initiates a connection to the server and that connection is held open so that the server can send data to the client whenever it wants to without the client having to specifically poll for that data.
A webSocket is a full, two-way data channel. Either client or server can send data in either direction.
SSE is a one-way channel, the server can send data to a listening client.
You can see these articles on comparing the pros/cons of each.
WebSockets vs Server-Sent Events - ably.com
Server-sent events vs. WebSockets - logrocket.com
Difference between server sent events and Websockets in HTML5 - geeksforgeeks.org
And, there are dozens of other articles here.
You may also want to be aware of socket.io which is a widely used layer built on top of webSockets that adds more features than either of these have (a named message layer, auto-reconnect, message acknowledgement, direct message response, built-in JSON support, etc...).
Any of these can do what you're asking for. Which of these to choose really depends upon the details of your requirements.
Try making a WebSocket server. There is ws package for Node.js, and alternatively socket.io. However if your client is a web client, you can use socket.io for easy-use and setup.

Interfacing data between functions in Node

I have a device that is connected to a Node server via WebSockets. To be able to query the device, a POST request to that server sends the necessary command via WebSockets. However, I'm not entirely sure what the best method of implenting getting the return is.
The flow is essentially:
Device connects to Node server via WebSockets
User sends POST request to endpoint on the same Node server
Node server sends the suitable command to the device via WebSockets
Device replies via WebSockets
This is where I'm stuck. How do I get the reply from WebSockets back to the POST request?
My first thoughts were as such:
The POST request knows what command has been sent
The device sends back the command as part of the WebSocket reply
Therefore, I can just have a simple array of messages from the device that the POST request function can poll, and if there's suitable reply (say within 2 seconds), reply with that data and delete the message from the array. Further down the line, I can delete any messages that have expired but are still in the array.
What are my other options? Presumably I could poll from the client doing the POST request or alternatively connect that client via a WebSocket.
This server supports 1 device and usually 1 user at a time, so there isn't really any worry that the server could become overwhelmed.

node.js (with socket.io) security?

since I am learning node.js I was wondering about something:
When I use node.js server to run a websocket, so that clients can connect (like on a website via javascript), it always listens public. Isn't that a security problem, that everyone in the world would be able to send data to the ip:port. They just have to connect to the server via the data that are written anyway within javascript and send / receive data?
I was thinking about a token, which would make sense in Java or Swift etc, but in javascript it can be seen anyway?!
TL;DR: yes, It's totally secure.
Every time the browser sends an HTTP request, there is a port waiting for the server's response. The difference between this to an open port is that an open port is open for everyone on the web. In an HTTP request or web socket, the port opens only to the server.

Alternate of server polling?

As we know, if running application also manage sessions in main memory then is there any way for server to send responses to all web clients/browsers for new recorded data in a database.
Remember: I have not made any request to server or polling to server for new records update..
Let server make responses without web request..
Objective :
No all web browsers making request or polling to server for every certain interval therefore reducing the performance issue with the application memory..
Am just against of making so many ajax calls from every web client..
Need your ideas from your past, if experienced similar..
read about websockets and socket.io.
basically with socket.io you have a connection open between browser (client) and server and server can send data which the client than receives as an event.
the client doesn't need to send a request to get that data, only open the web socket connection.
you can look at socket.io chat example: http://socket.io/get-started/chat/
WebSocket is the best and easy solution if you don't want to go through the hassle to learn Angular or others.
Both server-side and client-side can build WebSocket, and it acts as a bridge to transmit data back and forth.
I just created an easy solution for this.
Please check my new library wsm - WebSocket Manager, it works for both server-side and client-side.
Websocket Server can be built easily; this library includes several useful features.

How Websockets are implemented?

How Websockets are implemented?
What is the algorithm behind this new tech (in comparison to Long-Polling)?
How can they be better than Long-Polling in term of performance?
I am asking these questions because here we have a sample code of Jetty websocket implementation (server-side).
If we wait long enough, a timeout will occur, resulting in the
following message on the client.
And that is definately the problem I'm facing when using Long-polling. It stops the process to prevent server overload, doesn't it ?
How Websockets are implemented?
webSockets are implemented as follows:
Client makes HTTP request to server with "upgrade" header on the request
If server agrees to the upgrade, then client and server exchange some security credentials and the protocol on the existing TCP socket is switched from HTTP to webSocket.
There is now a lasting open TCP socket connecting client and server.
Either side can send data on this open socket at any time.
All data must be sent in a very specific webSocket packet format.
Because the socket is kept open as long as both sides agree, this gives the server a channel to "push" information to the client whenever there is something new to send. This is generally much more efficient than using client-driven Ajax calls where the client has to regularly poll for new information. And, if the client needs to send lots of messages to the server (perhaps something like a mnulti-player game), then using an already open socket to send a quick message to the server is also more efficient than an Ajax call.
Because of the way webSockets are initiated (starting with an HTTP request and then repurposing that socket), they are 100% compatible with existing web infrastructure and can even run on the same port as your existing web requests (e.g. port 80 or 443). This makes cross-origin security simpler and keeps anyone on either client or server side infrastructure from having to modify any infrastructure to support webSocket connections.
What is the algorithm behind this new tech (in comparison to
Long-Polling)?
There's a very good summary of how the webSocket connection algorithm and webSocket data format works here in this article: Writing WebSocket Servers.
How can they be better than Long-Polling in term of performance?
By its very nature, long-polling is a bit of a hack. It was invented because there was no better alternative for server-initiated data sent to the client. Here are the steps:
The client makes an http request for new data from the client.
If the server has some new data, it returns that data immediately and then the client makes another http request asking for more data. If the server doesn't have new data, then it just hangs onto the connection for awhile without providing a response, leaving the request pending (the socket is open, the client is waiting for a response).
If, at any time while the request is still pending, the server gets some data, then it forms that data into a response and returns a response for the pending request.
If no data comes in for awhile, then eventually the request will timeout. At that point, the client will realize that no new data was returned and it will start a new request.
Rinse, lather, repeat. Each piece of data returned or each timeout of a pending request is then followed by another ajax request from the client.
So, while a webSocket uses one long-lived socket over which either client or server can send data to the other, the long-polling consists of the client asking the server "do you have any more data for me?" over and over and over, each with a new http request.
Long polling works when done right, it's just not as efficient on the server infrastructure, bandwidth usage, mobile battery life, etc...
What I want is explanation about this: the fact Websockets keep an
open connection between C/S isn't quite the same to Long Polling wait
process? In other words, why Websockets don't overload the server?
Maintaining an open webSocket connection between client and server is a very inexpensive thing for the server to do (it's just a TCP socket). An inactive, but open TCP socket takes no server CPU and only a very small amount of memory to keep track of the socket. Properly configured servers can hold hundreds of thousands of open sockets at a time.
On the other hand a client doing long-polling, even one for which there is no new information to be sent to it, will have to regularly re-establish its connection. Each time it re-establishes a new connection, there's a TCP socket teardown and new connection and then an incoming HTTP request to handle.
Here are some useful references on the topic of scaling:
600k concurrent websocket connections on AWS using Node.js
Node.js w/1M concurrent connections!
HTML5 WebSocket: A Quantum Leap in Scalability for the Web
Do HTML WebSockets maintain an open connection for each client? Does this scale?
Very good explanation about web sockets, long polling and other approaches:
In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?
Long poll - request → wait → response. Creates connection to server like AJAX does, but keep-alive connection open for some time (not long though), during connection open client can receive data from server. Client have to reconnect periodically after connection is closed due to timeouts or data eof. On server side it is still treated like HTTP request same as AJAX, except the answer on request will happen now or some time in the future defined by application logic. Supported in all major browsers.
WebSockets - client ↔ server. Create TCP connection to server, and keep it as long as needed. Server or client can easily close it. Client goes through HTTP compatible handshake process, if it succeeds, then server and client can exchange data both directions at any time. It is very efficient if application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server so data is simply encrypted. support chart (very good)
Overall, sockets have much better performance than long polling and you should use them instead of long polling.

Categories