Cordova: Sockets, PushNotifications, or repeatedly polling server?

前端 未结 2 732
说谎
说谎 2020-12-18 11:00

I have a Cordova/PhoneGap app.

I\'d like to have some semblance of real-time updates when the app is in the foreground.

What\'s the least resource-intensive

2条回答
  •  旧巷少年郎
    2020-12-18 11:44

    Use websockets.

    A polling based approach introduces a minimum overhead of having to issue a request every X seconds to check for any new messages, which gives you a crappy trade-off: the lower the request rate, the less responsive your app is. xhr long polling reduces this cost somewhat by keeping an http request open for 30-60 seconds or so, allowing the server to send the response as soon as it can, but this still imposes a regular request interval to take place.

    A websocket is a persistent connection, meaning a connection is kept open for each client. This means memory usage, but I wouldn't fret too much. You will bottleneck on actual message traffic before persisted connections

    This is a really good read to give you an idea of what kind of scale is possible with websockets on node.js: http://www.jayway.com/2015/04/13/600k-concurrent-websocket-connections-on-aws-using-node-js/

    There are lots of options out there, two I would recommend are socket.io and faye. They are both very easy to get up and running. Both will also handle things for you like defining message channels, connect/disconnect protocols, and they have the added advantage of selecting the right transport that both the client and server both support. Socket.io 1.0+ (using engine.io) for example will start with long polling and upgrade to websockets if both endpoints support it, which can speed things up. Faye is a nice lightweight pub/sub system whereas socket.io is somewhat more involved, session based offering. One or the other might be a good choice depending on your needs.

    If minimizing your request load is your paramount concern, implementing websockets directly with the npm ws (which is what both socket.io and faye rely on) is also an option, but this is obviously more complex.

提交回复
热议问题