WebSocket in Ionic

There seems to be a lot of confusing discussion about using websocket in ionic apps, and very little if anything I can find concerning ionic 2 apps. I really need a websocket api for my ionic 2 app; that will work at lest on the browser platform plus android platform. Any suggestions?

1 Like

I advise to search for articles on using websockets and angular2. Just found a couple of good ones though Google that are a complete how-to that you can use.

Thanks, I’m using angular2-websocket. Its working fine, for receiving data from the server, but when trying to send data nothing gets sent it seems (although the send does trigger an onOpen event at the server).

My send is simply:


Repeated sends lead to nothing.
I’ve tested my web socket server using a regular Javascript program and it does indeed receive data fine in that case.
I don’t know any further how to debug my Ionic app… how can I find out where the send operation is failing?

I figured out the answer to this. You can’t just call send as is shown in the example for the package, and pretty much everywhere on the web. You need to subscribe to the observable that is returned, e.g.:

                res => { console.log(res)},
                err => {

I guess this is because the observable is destroyed without a subscriber and this kills the sent message before it gets a chance to be sent.


Hi Arnhrwd,

I am developing a similar application using web sockets in ionic 2. Is is possible for you to share the connection code for your web socket? I am having difficulties connecting to my server.

Thanks a lot

The code below also shows call backs that attempt to reconnect when the connection is lost.

import {$WebSocket} from 'angular2-websocket/angular2-websocket';
export class MyService {
    ws : any;
        this.ws = new $WebSocket("ws://hostname:port/websocket/path");
            res => {},
            function(x){return function(e) { console.log('connection error: ' + e.message); x.connect();}}(this),
            function(x){return function() { console.log('connection completed'); x.connect();}}(this)

And then when sending data:

            res => { console.log("send observer:" +res)},
            err => {
                console.log("send observer:" + err);

Note that you need the subscribe or otherwise the send request is destroyed before it is sent.

1 Like

We are trying to proxy the Websocket calls using angular2-websocket? Have some ideas how can we do this?

Please see here the dedicated post, thx

Hi everyone, I want to make a system in my app that recognizes that the user closed the application, they advised me to use websokets but I never worked with them, could they help me with this?