使用SilverLight构建插件式应用程序(九) —聊天插件客户端的实现
2008-10-30 11:48:57 来源:WEB开发网客户单服务重要的代码差不多就是这些,需要明白如何发送消息,如果进入消息接受模式。下面看看界面如何处理:
private void StartServer()
{
Uri uri = System.Windows.Browser.HtmlPage.Document.DocumentUri;
string host = uri.AbsoluteUri;
host = host.Substring(0, host.Length - uri.LocalPath.Length);
string servicePath = "/Services/WSChat.svc";
string serviceUri = host + servicePath;
chatSerrice = new ChatServer(this, serviceUri, App.GetLoginUser().UserName);
chatSerrice.Start();
chatSerrice.Join(App.GetLoginUser().UserName);
//
_Timer = new Timer(new TimerCallback(_Timer_Elapsed), null, 30000, Timeout.Infinite);
}
建立新的服务,然后定时发送心跳信息:
private void CreateChat(string friendName)
{
///
if (!chatUsers.ContainsKey(friendName))
{
UserChat userChat = new UserChat();
userChat.txtTitle.Text = "与 " + friendName + " 交谈中";
userChat.OnSend += (o, ev) =>
{
ev.From = App.GetLoginUser().UserName;
chatSerrice.Say(ev);
};
userChat.UserName = friendName;
userChat.OnCloseed += (o, ev) =>
{
chatUsers.Remove(ev);
for (int i = 0; i < canvasChat.Children.Count; i++)
{
if ((canvasChat.Children[i] as UserChat).UserName == ev)
{
canvasChat.Children.RemoveAt(i);
}
}
};
chatUsers.Add(friendName, userChat);
this.canvasChat.Children.Add(userChat);
}
}
针对每个不同的聊天对象,建立独立的窗口。
public void ProcessData(Object receivedData)
{
if (receivedData != null)
{
ChatMessage cm = receivedData as ChatMessage;
if (cm.Type > 0)
{
//聊天窗口是否包含
if (!chatUsers.ContainsKey(cm.From))
{
CreateChat(cm.From);
}
if (chatUsers.ContainsKey(cm.From))
{
string txt = "";
txt = cm.From + " 说:" + cm.Data + ""n"; ;
chatUsers[cm.From].txtChat.Text += txt;
}
}
}
}
接受到不同的信息之后,把对应的消息显示到不同的窗口上,免得混杂在一起:
至此,聊天的主要功能完成。
Tags:使用 SilverLight 构建
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接