javasocketsgwtchannel-api

Closing Channel with Google Channel API


I've written a client/server implementation of the Google Channel API using GWT and Java. I've looked everywhere on the internet and also in the Channel API to find out how to close a Channel when you are finished using it (each user can only have one channel open at a time, so this is very important for my app), but so far I've found nothing.

Does anyone know how to send the close socket request to Google to close a certain Channel's socket?


Solution

  • Apparently nobody on the internet has figured out (or needed to figure out) how to do this, so I just stared at the API overview long enough until it came to me. The secret is in the Javascript portion of the API, when you create the "socket" variable. The Javascript API states that the socket var also has a "close()" function. Considering I wrote my implementation in Java, that made it a little tricky for me as I had to dust off my knowledge of JSNI, and the socket var only existed during my "join" call.

    To remedy this, I created a global variable out of the socket variable, in this case called "globalSocket" and then later on wrote a separate JSNI close function that just called "close()" on the global socket variable. Worked like a charm after that.

    private native void join(String channelKey) /*-{
        var channel = new $wnd.goog.appengine.Channel(channelKey);
        var socket = channel.open();
        $wnd.globalSocket = socket;
        var self = this;
    
        socket.onmessage = function(evt) {
            var data = evt.data;
            self.@com.divint.roo.client.Channel::onMessage(Ljava/lang/String;)(data);
        };
    
        socket.onopen = function() {
            self.@com.divint.roo.client.Channel::onOpen()();
        };
    
        socket.onerror = function(error) {
            self.@com.divint.roo.client.Channel::onError(ILjava/lang/String;)(error.code, error.description);
        };
    
        socket.onclose = function() {
            self.@com.divint.roo.client.Channel::onClose()();
        };
    
    }-*/;
    
    private native void close() /*-{
        $wnd.globalSocket.close();
    }-*/;