将SuperSocket封装成类库之后可以将其集成进各种类型的应用,而不仅仅局限于控制台应用程序了,从而应用于不同的场景。这里以TelnetServer为例说明如何进行操作。
首先,创建一个C#类库项目LibSocketServer
添加SuperSocket引用(SuperSocket.Common.dll,SuperSocket.SocketBase.dll,SuperSocket.SocketEngine.dll),添加默认的日志框架log4net.dll引用。将log4net.config拷贝到项目文件夹的“Config”文件夹,然后设置它的“生成操作”为“内容”,设置它的“复制到输出目录”为“如果较新则复制”。
其次,添加SuperSocket完整的TelnetServer服务相关类,Socket服务管理类SocketServerManager。
其中SocketServerManager对Bootstrap的设置是SuperSocket封装为类库的关键。
TelnetSession.cs
usingSystem; usingSuperSocket.SocketBase; usingSuperSocket.SocketBase.Protocol; namespaceLibSocketServer.Server { publicclassTelnetSession:AppSession<TelnetSession> { protectedoverridevoidOnSessionStarted() { Console.WriteLine($"NewSessionConnected:{RemoteEndPoint.Address}"+ $"@{RemoteEndPoint.Port}."); Send("WelcometoSuperSocketTelnetServer."); } protectedoverridevoidHandleUnknownRequest(StringRequestInforequestInfo) { Console.WriteLine($"Unknownrequest{requestInfo.Key}."); Send("Unknownrequest."); } protectedoverridevoidHandleException(Exceptione) { Console.WriteLine($"Applicationerror:{e.Message}."); Send($"Applicationerror:{e.Message}."); } protectedoverridevoidOnSessionClosed(CloseReasonreason) { Console.WriteLine($"Session{RemoteEndPoint.Address}@{RemoteEndPoint.Port}"+ $"Closed:{reason}."); base.OnSessionClosed(reason); } } }
TelnetServer.cs
usingSystem; usingSuperSocket.SocketBase; usingSuperSocket.SocketBase.Config; namespaceLibSocketServer.Server { publicclassTelnetServer:AppServer<TelnetSession> { protectedoverrideboolSetup(IRootConfigrootConfig,IServerConfigconfig) { Console.WriteLine("TelnetServerSetup"); returnbase.Setup(rootConfig,config); } protectedoverridevoidOnStarted() { Console.WriteLine("TelnetServerOnStarted"); base.OnStarted(); } protectedoverridevoidOnStopped() { Console.WriteLine(); Console.WriteLine("TelnetServerOnStopped"); base.OnStopped(); } } }
AddCommand.cs
usingSystem; usingSystem.Linq; usingLibSocketServer.Server; usingSuperSocket.SocketBase.Command; usingSuperSocket.SocketBase.Protocol; namespaceLibSocketServer.Command { publicclassAddCommand:CommandBase<TelnetSession,StringRequestInfo> { publicoverridestringName=>"ADD"; publicoverridevoidExecuteCommand(TelnetSessionsession,StringRequestInforequestInfo) { Console.WriteLine($"{Name}command:{requestInfo.Body}."); session.Send(requestInfo.Parameters.Select(p=>Convert.ToInt32(p)).Sum().ToString()); } } }
EchoCommand.cs
usingSystem; usingLibSocketServer.Server; usingSuperSocket.SocketBase.Command; usingSuperSocket.SocketBase.Protocol; namespaceLibSocketServer.Command { publicclassEchoCommand:CommandBase<TelnetSession,StringRequestInfo> { publicoverridestringName=>"ECHO"; publicoverridevoidExecuteCommand(TelnetSessionsession,StringRequestInforequestInfo) { Console.WriteLine($"{Name}command:{requestInfo.Body}."); session.Send(requestInfo.Body); } } }
SocketServerManager.cs
usingSystem; usingSystem.Reflection; usingSuperSocket.SocketBase; usingSuperSocket.SocketEngine; namespaceLibSocketServer { publicclassSocketServerManager { privatereadonlyIBootstrap_bootstrap; publicboolStartup(intport) { if(!_bootstrap.Initialize()) { Console.WriteLine("SuperSocketFailedtoinitialize!"); returnfalse; } varret=_bootstrap.Start(); Console.WriteLine($"SuperSocketStartresult:{ret}."); returnret==StartResult.Success; } publicvoidShutdown() { _bootstrap.Stop(); } #regionSingleton privatestaticSocketServerManager_instance; privatestaticreadonlyobjectLockHelper=newobject(); privateSocketServerManager() { varlocation=Assembly.GetExecutingAssembly().Location; varconfigFile=$"{location}.config"; _bootstrap=BootstrapFactory.CreateBootstrapFromConfigFile(configFile); } publicstaticSocketServerManagerInstance { get { if(_instance!=null) { return_instance; } lock(LockHelper) { _instance=_instance??newSocketServerManager(); } return_instance; } } #endregion } }
再次,添加配置文件App.config到类库中,并设置其配置参数。 <?xmlversion="1.0"encoding="utf-8"?> <configuration> <configSections> <sectionname="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig,SuperSocket.SocketEngine"/> </configSections> <!--SuperSocket配置的根节点--> <superSocket> <!--服务器实例--> <servers> <servername="TelnetServer"serverTypeName="TelnetServerType"ip="Any"port="2021"></server> </servers> <!--服务器类型--> <serverTypes> <addname="TelnetServerType"type="LibSocketServer.Server.TelnetServer,LibSocketServer"/> </serverTypes> </superSocket> </configuration>
最后,创建控制台项目TelnetServerSample,添加项目引用LibSocketServer,然后在Program类中使用SocketServerManager进行SuperSocket的调用。
Program.cs
usingSystem; usingLibSocketServer; namespaceTelnetServerSample { classProgram { staticvoidMain() { try { //启动SuperSocket if(!SocketServerManager.Instance.Startup(2021)) { Console.WriteLine("FailedtostartTelnetServer!"); Console.ReadKey(); return; } Console.WriteLine("TelnetServerislisteningonport2021."); Console.WriteLine(); Console.WriteLine("Presskey'q'tostopit!"); Console.WriteLine(); while(Console.ReadKey().KeyChar.ToString().ToUpper()!="Q") { Console.WriteLine(); } //关闭SuperSocket SocketServerManager.Instance.Shutdown(); } catch(Exceptione) { Console.WriteLine("Exception:{0}",e.Message); } Console.WriteLine(); Console.WriteLine("TelnetServerwasstopped!"); Console.WriteLine("Pressanykeytoexit..."); Console.ReadKey(); } } }
GitHubSample
上述就是C#学习教程:SuperSocket封装成C#类库的步骤分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/903579.html