获取会话的连接和断开事件

关键字: 连接事件, 断开事件, OnSessionStarted, OnSessionClosed, NewSessionConnected, SessionClosed

AppSession 的虚方法 OnSessionStarted() 和 OnSessionClosed(CloseReason reason)

你可以覆盖基类的虚方法 OnSessionStarted() 和 OnSessionClosed(CloseReason reason) 用于在会话连接和断开时执行一些逻辑操作:

  1. public class TelnetSession : AppSession<TelnetSession>
  2. {
  3. protected override void OnSessionStarted()
  4. {
  5. this.Send("Welcome to SuperSocket Telnet Server");
  6. //add your business operations
  7. }
  8. protected override void OnSessionClosed(CloseReason reason)
  9. {
  10. //add your business operations
  11. }
  12. }

AppServer 的两个事件: NewSessionConnected 和 SessionClosed

订阅事件:

  1. appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);
  2. appServer.SessionClosed += new SessionHandler<AppSession, CloseReason>(appServer_SessionClosed);

定义事件处理方法:

  1. static void appServer_SessionClosed(AppSession session, CloseReason reason)
  2. {
  3. Console.WriteLine("A session is closed for {0}.", reason);
  4. }
  5. static void appServer_NewSessionConnected(AppSession session)
  6. {
  7. session.Send("Welcome to SuperSocket Telnet Server");
  8. }