使用SilverLight构建插件式应用程序(九) —聊天插件客户端的实现
2008-10-30 11:48:57 来源:WEB开发网上边这段代码基本是固定模式,表示使用channel模式进行访问WCF服务,打开完成服务之后,开始进行第一次通信,就是发送信条信息,然后进入消息等待模式:
void CompleteOpenChannel(IAsyncResult result)
{
channel = (IDuplexSessionChannel)result.AsyncState;
channel.EndOpen(result);
ChatMessage chatMessage = new ChatMessage();
chatMessage.From = UserName;
chatMessage.To = "SystemServer";
chatMessage.Data = System.DateTime.Now.ToString();
// Channel is now open. Send message
Message message =
Message.CreateMessage(channel.GetProperty<MessageVersion>(),
"WindCloud/WSChatService/Heart", chatMessage);
IAsyncResult resultChannel =
channel.BeginSend(message, new AsyncCallback(OnSend), channel);
if (resultChannel.CompletedSynchronously)
{
CompleteOnSend(resultChannel);
}
//Start listening for callbacks from the service
ReceiveLoop(channel);
}
至此,客户端就会一直等待服务器发来消息,一旦接收到消息,就进入下边的消息处理过程:
void ReceiveLoop(IDuplexSessionChannel channel)
{
// Start listening for callbacks.
IAsyncResult result = channel.BeginReceive(new AsyncCallback(OnReceiveComplete), channel);
if (result.CompletedSynchronously) CompleteReceive(result);
}
void OnReceiveComplete(IAsyncResult result)
{
if (result.CompletedSynchronously)
return;
else
CompleteReceive(result);
}
void CompleteReceive(IAsyncResult result)
{
//A callback was received so process data
IDuplexSessionChannel channel = (IDuplexSessionChannel)result.AsyncState;
try
{
Message receivedMessage = channel.EndReceive(result);
// Show the service response in the UI.
if (receivedMessage != null)
{
ChatMessage text = receivedMessage.GetBody<ChatMessage>();
_UiThread.Post(Client.ProcessData, text);
}
ReceiveLoop(channel);
}
catch (CommunicationObjectFaultedException exp)
{
_UiThread.Post(delegate(object msg) { System.Windows.Browser.HtmlPage.Window.Alert(msg.ToString()); }, exp.Message);
}
}
Tags:使用 SilverLight 构建
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接