【问题标题】:Server send events with Grails服务器使用 Grails 发送事件
【发布时间】:2013-12-29 11:21:57
【问题描述】:

我们想要制作一个聊天应用程序,用户可以在其中输入一些文本,然后其他用户会看到。 Ext.Ajax.request 是被调用的函数,用于通过 Ajax 向服务器发送数据。

这是 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);
    }
});

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
    }
}

以下示例将接收服务器发送事件,这些事件将从 grails 应用程序发送:

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);
}

我们发现 grails 插件氛围和事件推送,但示例仅显示 websockets 而不是服务器端事件。我们不知道如何使用事件推送插件从 grails 服务器广播文本。有人可以帮忙吗?

【问题讨论】:

标签: javascript ajax grails extjs sencha-architect


【解决方案1】:

您可以在 Grails 服务中发送您的服务器事件。 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]) 
}

要在客户端接收这个,你需要插件模块:

<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>

data 参数是来自服务器事件的响应。

请务必检查文档链接中的 Tomcat 配置,这是重要的一步。

【讨论】:

    猜你喜欢
    • 2015-06-16
    • 1970-01-01
    • 2013-05-01
    • 2015-09-24
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多