SuperSocket封装成C#类库的步骤
作者:xhubobo 发布时间:2023-09-05 02:36:33
标签:C#,SuperSocket,封装
将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
来源:https://www.cnblogs.com/xhubobo/p/14118764.html


猜你喜欢
- 简介java中可以被称为Number的有byte,short,int,long,float,double和char,我们在使用这些Nubme
- XListview是一个非常受欢迎的下拉刷新控件,但是已经停止维护了。之前写过一篇XListview的使用介绍,用起来非常简单,这两天放假无
- 本文实例为大家分享了Android实现3D层叠式卡片图片展示的具体代码,供大家参考,具体内容如下先看效果好了效果看了,感兴趣的往下看哦!整体
- 一、ThreadPoolThreadPool是.Net Framework 2.0版本中出现的。ThreadPool出现的背景:Thread
- 简单的实现了一个树的结构,很不完善!后续参考一些其他代码的实现。试图实现叶子存在可变的节点,能够用来解析xml文件。叶子的代码:packag
- eclipse中改变默然的workspace的方法可以有以下几种:1.在创建project的时候,手动选择使用新的workspace,如创建
- 本文实例为大家分享了WPF实现半圆形导航菜单的具体代码,供大家参考,具体内容如下实现效果如下:思路:扇形自定义控件组合成半圆型菜单,再通过c
- 解决@NotBlank不生效在项目开发中,发现一个类中包含有另外一个类,这种包含关系的类上的@NotBlank校验不生效,后来发现需要在内部
- springboot 统一设置时区控制springboot服务的时区为东八区@SpringBootApplicationpublic cla
- Dagger2注入框架原理简要分析使用Dagger2需要的依赖:implementation 'com.google.dagger:
- 本文实例讲述了ActiveMQ在C#中的应用。分享给大家供大家参考,具体如下:ActiveMQ是个好东东,不必多说。ActiveMQ提供多种
- 1. 背景我们都知道,Compose可以使用mutableStateOf和UI进行绑定,改变值之后,就可以改变UI。var value by
- 所谓文件的断点续传,就是一个线程传输文件,另一个线程控制传输标识,以达到暂停文件效果、恢复文件上传的效果。本demo使用最基本的线程之间的通
- android电话管理器(TelephonyManger)实例:TelephonyManger是管理电话状态、网络信息的服务类。添加权限:&
- 这篇文章主要介绍了Java import导入及访问控制权限修饰符过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- 废话不多说,我们先来认识一下这个GDI+,看看它到底长什么样。GDI+:Graphics Device Interface Plus也就是图
- 前言延迟初始化 是一种将对象的创建延迟到第一次需要用时的技术,换句话说,对象的初始化是发生在真正需要的时候才执行,值得注意的是,术语&nbs
- SpeSqliteManager4Android改动日志2023.2.14 完成SQLiteOpenHelper 2023.2.23 完成r
- 前言网上百度了很多FTP的java 工具类,发现文章代码都比较久远,且代码臃肿,即使搜到了代码写的还可以的,封装的常用操作方法不全面,于是自
- Unity打开Unity Ctrl+9,打开Unity商店,下载TexturePacker Importer插件这个插件是用来解析图集文件的