您的位置:首页 > 编程语言 > Java开发

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

2011-10-14 15:35 295 查看
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中还有应用到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: