Websocket angular and php

Asked

Viewed 105 times

0

Hello, I have a websocket in php and an angular Factory. I need to know, when there is, or does not exist, connection with websocket, in the part of the code send, socket.send(JSON.stringify(data)); of this Factory

.factory('socket', [function ($rootScope) {
var wsUri = "ws://162.243.172.112:1234";//localhost:1234
try{
    var socket = new WebSocket(wsUri);
    }catch(e){
        socket.onerror = function(ev){
            console.log(ev);
            alert("Falha");
        }
    }


return {
    send: function (data) {
        socket.send(JSON.stringify(data));

    },
    message: function(callback){
        socket.onmessage = function(ev) {
            var result = JSON.parse(ev.data); //PHP sends Json data
            //console.log(result);
            callback(result);

            $rootScope.$apply(function () {
                $rootScope.mensagens=result;
            });

        };
    },

    error: function(callback){
        socket.onerror = function(ev){
            console.log(ev);
            alert("Falha");
        }
    }

};

}])

  • It would be there in the }catch(e){

  • Yeah, but nothing shows up on the console, putting console.log(e). Only one message appears, like: Websocket Connection to 'Ws://162.xxx.xxx/' failed: Error in Connection establishment: net::ERR_CONECTION_REFISED and points to line 91 of the file, which is: var socket = new Websocket(wsUri);

  • But then I didn’t mention the console.log, I said you have to use the catch, if understood you want to test if the websocket works right? The catch is the solution, and just add a return; inside it and create a function to use the alternative to WS.

  • Right @Guilhermenascimento, but I want my app to recognize when there is no connection, when the websocket is not working, to send a warning to the user and not just change the WS. Because if the connection goes down, I have to reconnect the websocket and the user, you know? I don’t have an alternative WS.

  • I understood yes, so just use the catch and the the socket.onerror combined with a callback to request for the user this. I didn’t say alternate WS, I said anything alternative, like even a request message is something alternative

  • See if this modification, which I did in the code, here in the post, is right with what you said.

  • @Guilhermenascimento, see if the code is right, now.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.