anar
anar

Reputation: 41

Server send events with Grails

We want to make a chat application where user inputs some text and then other users see that. Ext.Ajax.request is the function being called to send data to the server via Ajax.

This is the code in Sencha Architect 3:

var panel = button.up();
var input = panel.getComponent("inputField");
console.debug("Message: " + input.getValue());


Ext.Ajax.request({
    url: '/Chat/chatMain/send',
    params: {
        message: input.getValue()
    },
    success: function(response){
        console.log("Message successfully send.");
    },
    failure: function(response){
        console.log("ERROR!");
        console.log('server-side failure with status code ' + response.status);
    }
});

Chat Controller in Grails:

class ChatMainController {

    def send(){ 
    //code for sending data back to client
    //params.message contains message from browser it should be broadcast
    //with server-side events
    //event('sms', data) // will trigger registered browsers on 'sms' topic
    }
}

Below example will receive server-send events which will be send from grails application:

var source = new EventSource('/Chat/chatMain/receive');

source.addEventListener('sms', showSms, false);

source.onmessage = function (event) {
  // a message without a type was fired
  showSms(event);
};

function showSms(e){
    console.log(e.data);
}

We found grails plugins atmosphere and events push but the examples only show websockets not server-side event. We don't know how to broadcast text from grails server with use of events push plugin. Can anybody help?

Upvotes: 3

Views: 1861

Answers (1)

user800014
user800014

Reputation:

You can send your server event in a Grails service. The plugin page show's an example:

MyService.groovy

//will receive client events from 'saveTodo' topic
@Listener(namespace='browser') saveTodo(Map data){
  //...
  // will trigger registered browsers on 'savedTodo' topic
  event([namespace: 'browser', topic: 'savedTodo', data: data]) 
}

To receive this in the client you need to require the plugin module:

<r:require module="grailsEvents"/>
<r:script>
  var grailsEvents = new grails.Events("http://localhost:8080/app/");
  grailsEvents.send('saveTodo', data); //will send data to server topic 'saveTodo'
  //will listen for server events on 'savedTodo' topic
  grailsEvents.on('savedTodo', function(data){...}); 
</r:script>

The data parameter is the response from the server event.

Make sure to check the Tomcat configuration in the link of the docs, this is an important step.

Upvotes: 0

Related Questions