案例学习BlazeDS+Spring之十:Chat(

46 篇文章 0 订阅
 

Chat:

该DEMO展示的是BlazeDS的消息服务,是一个使用发布/订阅者模式的简单聊天室。


一、运行DEMO:
1、运行程序:http://localhost:8400/spring-flex-testdrive/chat/index.html;
2、在另一个浏览器窗口访问同样的URL,打开第二个chat程序实例。
3、在一个chat客户端输入消息,单击“Send”,这个消息显示在两个chat客户端里。

二、理解代码:

1、chat.mxml的Producer/Consumer

消息服务管理一组Flex客户端能发布和订阅的destination集合。Flex提供Producer和Consumer两个组件用于发布和订阅destination。使用Consumer类的subscribe方法来订阅目标(destination),当有消息发布到你订阅的目标时,消息事件会在Consumer上触发。
<mx:Producer id="producer" destination="chat" channelSet="{cs}"/>
<mx:Consumer id="consumer" destination="chat" channelSet="{cs}" message="messageHandler(event.message)"/>

2、chat.mxml channelSet
Producer和Consumer的channelSet是cs,destination是chat。
ChanelSetAPI允许你在运行时动态的定义端点,在这个例子中,端点的URL是硬编码在程序中的,在真实情况下,客户端程序通常动态读入这些参数。例如,客户端程序在启动时使用HTTPService加载XML文件读入这些参数。加入到channelSet的第一个通道作为首选通道用来尝试连接服务器,如果首选通道失败,系统将尝试使用定义在channelSet中的第二个通道来连接。
        <mx:ChannelSet id="cs">
            <mx:StreamingAMFChannel url="http://localhost:8400/spring-flex-testdrive/messagebroker/streamingamf"/>
            <mx:AMFChannel url="http://localhost:8400/spring-flex-testdrive/messagebroker/amflongpolling"/>

            <mx:AMFChannel url="http://localhost:8400/spring-flex-testdrive/messagebroker/amfpolling"/>
        </mx:ChannelSet>
程序在启动时consumer即订阅chat消息。
consumer.subscribe();   

3、chat.mxml 异步消息

发送消息是通过建立一个异步消息,由product发送出去。
var message:IMessage = new AsyncMessage();
message.body.userId = userId.text;
message.body.chatMessage = msg.text;
producer.send(message);

AsyncMessage的body是Object类型,是消息正文包含需要传递到远程目标的特定数据。

4、consumer接收消息事件

当有消息事件发生时,会触发consumer上的message事件,程序通过messageHandler来处理。
private function messageHandler(message:IMessage):void
{
    log.text += message.body.userId + ": " + message.body.chatMessage + "\n";   
}

5、flex-servlet.xml

打开flex-servlet.xml,查看消息服务配置。消息服务使用<flex:message-broker />里的<flex:message-service />来配置。 
    <flex:message-broker>
        <flex:message-service
            default-channels="my-streaming-amf,my-longpolling-amf,my-polling-amf" />
        <flex:secured />
    </flex:message-broker>
    message-service的默认通道my-streaming-amf,my-longpolling-amf,my-polling-amf在WEB-INF\flex\services-config.xml中定义。

6、chat消息服务配置

在flex-servlet.xml中,使用<flxe:message-destination id="chat" />来配置Chat的消息服务。

三、小结:

使用BlazeDS的消息服务做聊天室,在后台只需做消息服务配置即可,发布/订阅者模式的核心部分已由BlazeDS实现,但这只是简单的聊天程序罢了。消息服务的这种特性,在后面的几个DEMO中还有应用到。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值