Search code examples
google-app-enginechannel-api

Message failure in channel api


I am running a gae web app on localhost. I have successfully generated a token from goog.channel and send it to client. Where client is able to accept the token and tries to open connection. The problem is that, I am sending a message from my servlet class and nothing is happening in client side.

Below are my codes:

Server Side:

//for generating token 
 ChannelService channelService=ChannelServiceFactory.getChannelService();
                    token = channelService.createChannel(userid);
//for sending message
ChannelService channelService=ChannelServiceFactory.getChannelService();
            channelService.sendMessage(new ChannelMessage(userid, message));

    //in appengine-web.xml
     <inbound-services>
            <service>channel_presence</service>
      </inbound-services>

Javascript:

function getToken(){                        
        var xmlhttpreq=new XMLHttpRequest();            
        xmlhttpreq.open('GET',host+'/channelapi_token?q='+user,false);
        xmlhttpreq.send();
        xmlhttpreq.onreadystatechange=alert(xmlhttpreq.responseText);
        token=xmlhttpreq.responseText;
        setChannel();
}

function setChannel(){
        alert(token);//iam receiving right token here
        channel=new goog.appengine.Channel(token);
        socket=channel.open();
        socket.open=alert('socket opened');//this message alerts
        socket.onmessage=alert('socket onmessage');//this message alerts
        socket.onerror=alert('socket onerror');//this message alerts
        socket.onclose=alert('socket onclose');//this message alerts
}

There are no exceptions while sending message from channelservice. Also the client side is repeatly making a get request to my server:

http://localhost:8888/_ah/channel/dev?command=poll&channel=channel-h1yphg-vivems@gmail.com&client=connection-3

What's the wrong happening here? Thanks in advance.


Solution

  • You're calling alert(...) and assigning its return value to your message handlers. You should assign a function to these handlers instead:

        socket.onopen = function() {
          alert('socket opened');
        };
        // etc
        // Note that message takes a parameter:
        socket.onmessage = function(evt) {
          alert('got message: ' + evt.data);
        };
    

    Note you can also do this like:

    function onMessage(evt) {
      // do something
    }
    
    socket.onmessage = onMessage;
    

    Note that you're not assigning onMessage(), which will call onMessage and assign its return value.