服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - SuperSocket封装成C#类库的步骤

SuperSocket封装成C#类库的步骤

2022-10-26 13:28xhubobo C#

这篇文章主要介绍了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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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到类库中,并设置其配置参数。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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#类库的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/xhubobo/p/14118764.html

延伸 · 阅读

精彩推荐
  • C#C#实现同Active MQ通讯的方法

    C#实现同Active MQ通讯的方法

    这篇文章主要介绍了C#实现同Active MQ通讯的方法,简单分析了Active MQ的功能及C#与之通讯的实现技巧,需要的朋友可以参考下...

    kagula6752021-11-30
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127292021-11-25
  • C#C# 在项目中引用x86 x64的非托管代码的方法

    C# 在项目中引用x86 x64的非托管代码的方法

    使用宏最简单的方法是编译两个版本,编译多个版本可以点击配置管理器,然后创建x86和x64,然后版本添加宏,这样就可以判断宏来使用不同的dll。这篇文...

    C#教程网11912022-02-20
  • C#C#实现将浮点数表示的货币数量以汉字大写形式输出的方法

    C#实现将浮点数表示的货币数量以汉字大写形式输出的方法

    这篇文章主要介绍了C#实现将浮点数表示的货币数量以汉字大写形式输出的方法,涉及C#针对浮点数的遍历与字符替换操作技巧,具有一定参考借鉴价值,需要的...

    北风其凉3872021-10-11
  • C#相对路径和绝对路径的写法总结

    相对路径和绝对路径的写法总结

    本文主要对相对路径和绝对路径的写法进行总结。具有一定的参考价值,下面跟着小编一起来看下吧...

    gina之编程花园7832021-12-20
  • C#C#9.0主要特性的一些想法

    C#9.0主要特性的一些想法

    这篇文章主要给大家介绍了关于C#9.0主要特性的一些想法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋...

    技术译站9332022-10-13
  • C#C#插入图片到Excel表格单元格代码详解

    C#插入图片到Excel表格单元格代码详解

    在本篇文章里小编给大家整理了关于C#插入图片到Excel表格单元格的具体方法和实例代码,需要的朋友们可以学习下。...

    sunny蓝鱼3452022-07-28
  • C#WPF 在image控件用鼠标拖拽出矩形的实现方法

    WPF 在image控件用鼠标拖拽出矩形的实现方法

    这篇文章主要介绍了WPF 在image控件用鼠标拖拽出矩形的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    lindexi8842022-02-27