SuperSocket封装成C#类库的步骤

 更新时间:2021年01月07日 08:56:42   作者:xhubobo  
这篇文章主要介绍了SuperSocket封装成C#类库的步骤,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下

将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

using System;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
 
namespace LibSocketServer.Server
{
    public class TelnetSession : AppSession<TelnetSession>
    {
        protected override void OnSessionStarted()
        {
            Console.WriteLine($"New Session Connected: {RemoteEndPoint.Address} " +
                              $"@ {RemoteEndPoint.Port}.");
            Send("Welcome to SuperSocket Telnet Server.");
        }
 
        protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
        {
            Console.WriteLine($"Unknown request {requestInfo.Key}.");
            Send("Unknown request.");
        }
 
        protected override void HandleException(Exception e)
        {
            Console.WriteLine($"Application error: {e.Message}.");
            Send($"Application error: {e.Message}.");
        }
 
        protected override void OnSessionClosed(CloseReason reason)
        {
            Console.WriteLine($"Session {RemoteEndPoint.Address} @ {RemoteEndPoint.Port} " +
                              $"Closed: {reason}.");
            base.OnSessionClosed(reason);
        }
    }
}

TelnetServer.cs

using System;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
 
namespace LibSocketServer.Server
{
    public class TelnetServer : AppServer<TelnetSession>
    {
        protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
        {
            Console.WriteLine("TelnetServer Setup");
            return base.Setup(rootConfig, config);
        }
 
        protected override void OnStarted()
        {
            Console.WriteLine("TelnetServer OnStarted");
            base.OnStarted();
        }
 
        protected override void OnStopped()
        {
            Console.WriteLine();
            Console.WriteLine("TelnetServer OnStopped");
            base.OnStopped();
        }
    }
}

AddCommand.cs

using System;
using System.Linq;
using LibSocketServer.Server;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
 
namespace LibSocketServer.Command
{
    public class AddCommand : CommandBase<TelnetSession, StringRequestInfo>
    {
        public override string Name => "ADD";
        public override void ExecuteCommand(TelnetSession session, StringRequestInfo requestInfo)
        {
            Console.WriteLine($"{Name} command: {requestInfo.Body}.");
            session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
        }
    }
}

EchoCommand.cs

using System;
using LibSocketServer.Server;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
 
namespace LibSocketServer.Command
{
    public class EchoCommand : CommandBase<TelnetSession, StringRequestInfo>
    {
        public override string Name => "ECHO";
        public override void ExecuteCommand(TelnetSession session, StringRequestInfo requestInfo)
        {
            Console.WriteLine($"{Name} command: {requestInfo.Body}.");
            session.Send(requestInfo.Body);
        }
    }
}

SocketServerManager.cs

using System;
using System.Reflection;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
 
namespace LibSocketServer
{
    public class SocketServerManager
    {
        private readonly IBootstrap _bootstrap;
 
        public bool Startup(int port)
        {
            if (!_bootstrap.Initialize())
            {
                Console.WriteLine("SuperSocket Failed to initialize!");
                return false;
            }
 
            var ret = _bootstrap.Start();
            Console.WriteLine($"SuperSocket Start result: {ret}.");
 
            return ret == StartResult.Success;
        }
 
        public void Shutdown()
        {
            _bootstrap.Stop();
        }
 
        #region Singleton
 
        private static SocketServerManager _instance;
        private static readonly object LockHelper = new object();
 
        private SocketServerManager()
        {
            var location = Assembly.GetExecutingAssembly().Location;
            var configFile = $"{location}.config";
            _bootstrap = BootstrapFactory.CreateBootstrapFromConfigFile(configFile);
        }
 
        public static SocketServerManager Instance
        {
            get
            {
                if (_instance != null)
                {
                    return _instance;
                }
 
                lock (LockHelper)
                {
                    _instance = _instance ?? new SocketServerManager();
                }
 
                return _instance;
            }
        }
 
        #endregion
    }
}

再次,添加配置文件App.config到类库中,并设置其配置参数。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="superSocket"
                 type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/>
    </configSections>
 
    <!-- SuperSocket配置的根节点 -->
    <superSocket>
        <!-- 服务器实例 -->
        <servers>
            <server name="TelnetServer" serverTypeName="TelnetServerType" ip="Any" port="2021"></server>
        </servers>
 
        <!-- 服务器类型 -->
        <serverTypes>
            <add name="TelnetServerType" type="LibSocketServer.Server.TelnetServer, LibSocketServer" />
        </serverTypes>
    </superSocket>
</configuration>

最后,创建控制台项目TelnetServerSample,添加项目引用LibSocketServer,然后在Program类中使用SocketServerManager进行SuperSocket的调用。

Program.cs

using System;
using LibSocketServer;
 
namespace TelnetServerSample
{
    class Program
    {
        static void Main()
        {
            try
            {
                //启动SuperSocket
                if (!SocketServerManager.Instance.Startup(2021))
                {
                    Console.WriteLine("Failed to start TelnetServer!");
                    Console.ReadKey();
                    return;
                }
 
                Console.WriteLine("TelnetServer is listening on port 2021.");
                Console.WriteLine();
                Console.WriteLine("Press key 'q' to stop it!");
                Console.WriteLine();
                while (Console.ReadKey().KeyChar.ToString().ToUpper() != "Q")
                {
                    Console.WriteLine();
                }
 
                //关闭SuperSocket
                SocketServerManager.Instance.Shutdown();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
            }
 
            Console.WriteLine();
            Console.WriteLine("TelnetServer was stopped!");
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }
}

GitHub Sample

以上就是SuperSocket封装成C#类库的步骤的详细内容,更多关于SuperSocket封装成C#类库的资料请关注脚本之家其它相关文章!

相关文章

  • C#绘制飞行棋地图小程序

    C#绘制飞行棋地图小程序

    这篇文章主要介绍了C#绘制飞行棋地图小程序的相关资料,非常不错,具有参考借鉴价值,对c飞行棋地图相关知识感兴趣的朋友一起看看吧
    2016-09-09
  • C#通过委托调用Button单击事件的方法

    C#通过委托调用Button单击事件的方法

    本文给大家分享的是通过委托取消Button事件switch-case的方法,十分的简单实用,有需要的小伙伴可以参考下。
    2015-05-05
  • async and await 的入门基础操作

    async and await 的入门基础操作

    本篇文章对async and await 的入门基础操作进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • c#创建浮动工具栏功能示例

    c#创建浮动工具栏功能示例

    这篇文章主要介绍了c#创建浮动工具栏功能示例,大家参考使用吧
    2013-12-12
  • C# XML基础入门小结(XML文件内容增删改查清)

    C# XML基础入门小结(XML文件内容增删改查清)

    本文主要介绍了C# XML基础入门小结(XML文件内容增删改查清),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • 浅析C# AsyncLocal如何在异步间进行数据流转

    浅析C# AsyncLocal如何在异步间进行数据流转

    在异步编程中,处理异步操作之间的数据流转是一个比较常用的操作,C#异步编程提供了一个强大的工具来解决这个问题,那就是AsyncLocal,下面我们就来看看AsyncLocal的原理和用法吧
    2023-08-08
  • 使用c#实现随机数猜数游戏的示例代码

    使用c#实现随机数猜数游戏的示例代码

    这篇文章主要介绍了使用c#实现随机数猜数游戏的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • C#之HttpClient的同步使用方式

    C#之HttpClient的同步使用方式

    这篇文章主要介绍了C#之HttpClient的同步使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • C# 获取指定QQ头像绘制圆形头像框GDI(Graphics)的方法

    C# 获取指定QQ头像绘制圆形头像框GDI(Graphics)的方法

    某论坛的评论区模块,发现这功能很不错,琢磨了一晚上做了大致一样的,用来当做 注册模块 的头像绑定功能,下面通过实例代码给大家介绍下C# 获取指定QQ头像绘制圆形头像框GDI(Graphics)的方法,感兴趣的朋友一起看看吧
    2021-11-11
  • C#强制类型转换小结

    C#强制类型转换小结

    任何一门编程语言均有相关数据类型。C#也不例外,不过转换过程要注意小类型能转换成大类型,但大类型一般不能转换成小类型,下面小编给大家详解C#强制类型转换小结,需要的朋友参考下吧
    2017-07-07

最新评论