关闭

轻易实现基于linux或win运行的聊天服务端程序

发表于:2014-10-27 09:47

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:smark    来源:51Testing软件测试网采编

  以上一个简单的聊取室的登进和聊天的功能,不过还有一个需要我们去处理的就是当用户断开后如果反映给其他用户.在EC中监控连接断开的过程需要通过一个AppModel来监控,发布有连接断开了则向其他连接发送登出信息,代码如下:
public class AppModel : EC.IAppModel
{
public void Init(EC.IApplication application)
{
application.Disconnected += (o, e) =>
{
Beetle.Express.IChannel channel = e.Session.Channel;
Chat.Signout msg = new Signout();
msg.Name = channel.Name;
msg.From = channel.EndPoint.ToString();
foreach (Beetle.Express.IChannel other in application.Server.GetOnlines())
{
if (other != channel)
application.Server.Send(msg, other);
}
};
}
public string Name
{
get { return "AppModel"; }
}
public string Command(string cmd)
{
throw new NotImplementedException();
}
}
  EC提供一个IAppModel的自定义功能,通过AppModel可以监控用户会话,和处理全局消息的能力;在以后的文章再详细介绍.
  客户端
  EC同样提供便利的Client功能对象,你只需要定义简单的代码就可以向对应的服务端发送和接收相应的消息来处理.
EC.ProtoClient mClient = new EC.ProtoClient("127.0.0.1");
mClient.Receive = (o, p) => {
if (p.Message is Say)
{
Invoke(new Action<Say>(OnSay), p.Message);
}
else if (p.Message is Login)
{
Invoke(new Action<Login>(OnLogin), p.Message);
}
else if (p.Message is Signout)
{
Invoke(new Action<Signout>(OnSignout), p.Message);
}
};
mClient.Send(new Say{ Content=t"你好"});
  借助于Xamarin我们还可以同样的方式把功能移植到不同平台下运行如android,ios等
private IServiceChannel mClient = new ServiceChannel("10.0.2.2",10034);
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
ServiceChannel.Register (typeof(MainActivity).Assembly);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
EditText name = FindViewById<EditText> (Resource.Id.txtname);
EditText say = FindViewById<EditText> (Resource.Id.txtsay);
TextView content = FindViewById<TextView> (Resource.Id.txtContent);
mClient.Receive = (o, p) => {
content.Post(delegate {
content.Append(p.Message.ToString());
});
};
FindViewById<Button> (Resource.Id.btnlogin).Click += delegate {
Login login = new Login();
login.Name = name.Text;
mClient.Send(login);
};
FindViewById<Button> (Resource.Id.btnsay).Click += delegate {
Say s = new Say{ Content=say.Text};
mClient.Send(s);
};
// Get our button from the layout resource,
// and attach an event to it
}
  这样一个多平台的基础聊天功能就完成了
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号