SuperSocket 1.5 Documentation译文 2 ----- 实现你的AppServer和AppSession
什么是AppSession?
AppSession表示邏輯socket連接,基于連接的操作應(yīng)在該類中定義。您可以使用這個類的實例,將數(shù)據(jù)發(fā)送到TCP客戶端,接收數(shù)據(jù)連接或關(guān)閉連接。
什么是AppServer?
AppServer表示監(jiān)聽所有客戶端連接的服務(wù)端實例。在理想的情況下,我們可以從AppServer得到我們想找到的任何會話。它應(yīng)該被定義在應(yīng)用程序級別的操作和邏輯里。
創(chuàng)建你的?AppSession
您可以重寫基類AppSessions的業(yè)務(wù)
public class TelnetSession : AppSession<TelnetSession> {protected override void OnSessionStarted(){this.Send("Welcome to SuperSocket Telnet Server");}protected override void HandleUnknownRequest(StringRequestInfo requestInfo){this.Send("Unknow request");}protected override void HandleException(Exception e){this.Send("Application error: {0}", e.Message);}protected override void OnSessionClosed(CloseReason reason){//添加在會話關(guān)閉后你的業(yè)務(wù)邏輯代碼base.OnSessionClosed(reason);} }
?
在上面的代碼中,客戶端連接上的時候服務(wù)端發(fā)送歡迎消息,這段代碼也重寫了其他用來處理我們自己邏輯的方法。
根據(jù)業(yè)務(wù)需求你可以為你的會話添加一個新的屬性,創(chuàng)建一個將用于游戲服務(wù)端的AppSession
public class PlayerSession :AppSession<PlayerSession> {public int GameHallId { get; internal set; }public int RoomId { get; internal set; } }?
關(guān)于命令
在第一份文檔中,我們討論了有關(guān)命令,現(xiàn)在我們在這里修改了一點:
public class ECHO : CommandBase<AppSession, StringRequestInfo> {public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo){session.Send(requestInfo.Body);} }?
在該命令的代碼中,你應(yīng)該已經(jīng)發(fā)現(xiàn),父類是CommandBase,其中有一個泛型類型參數(shù)AppSession。這是的默認AppSession。如果你想使用新的AppSession,把你的AppSession類型作為參數(shù)傳遞,否則服務(wù)器無法解析你的命令:
public class ECHO : CommandBase<PlayerSession, StringRequestInfo> {public override void ExecuteCommand(PlayerSession session, StringRequestInfo requestInfo){session.Send(requestInfo.Body);} }?
創(chuàng)建你的?AppServer
如果你想使用你的AppSession作為會話,你必須修改你的AppServer來使用它:
public class TelnetServer : AppServer<TelnetSession> {}現(xiàn)在 TelnetSession 將可以用在 TelnetServer 的會話中。
這里也有很多保護類方法你可以重寫
public class TelnetServer : AppServer<TelnetSession> {protected override bool Setup(IRootConfig rootConfig, IServerConfig config){return base.Setup(rootConfig, config);}protected override void OnStartup(){base.OnStartup();}protected override void OnStopped(){base.OnStopped();} }?
優(yōu)點
允許你根據(jù)業(yè)務(wù)需求拓展的SuperSocket來實現(xiàn)你的AppSession和App Server,你也可以看到會話的連接事件和關(guān)閉事件,服務(wù)器的啟動和停止事件。
在服務(wù)端的Setup()方法中,您也可以讀取自己定制的配置,總之,它有很多功能,而這正是你需要很容易創(chuàng)建的一個socket服務(wù)器。
轉(zhuǎn)載于:https://www.cnblogs.com/idoudou/articles/2863447.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的SuperSocket 1.5 Documentation译文 2 ----- 实现你的AppServer和AppSession的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Silverlight - Out of
- 下一篇: C# 线程知识--使用Task执行异步操