以上一个简单的聊取室的登进和聊天的功能,不过还有一个需要我们去处理的就是当用户断开后如果反映给其他用户.在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 } |
这样一个多平台的基础聊天功能就完成了