zoukankan      html  css  js  c++  java
  • C# 使用SuperSocket

    一、需求场景

      (1)使用SuperSocket进行网络通信

    二、所需软件

      (1)SocketTool

    三、实现步骤

      (1)使用Nuget管理器安装SuperSocket.Engine

     该插件已经包含(SuperSocket插件)

    注意:SuperSocket里面集成了log4net(如果你的程序中已经引入了log4net,一定要注意版本是否一致,如果不一致,会报错)

      (2)新建一个SocketSession类,继承自AppSession

     1 using SuperSocket.SocketBase;
     2 using System;
     3 using System.Text;
     4 using SuperSocket.SocketBase.Protocol;
     5 
     6 namespace SuperSocketBlog
     7 {
     8     public class SocketSession : AppSession<SocketSession>
     9     {
    10         public override void Send(string message)
    11         {
    12             Console.WriteLine("发送消息:" + message);
    13             base.Send(message);
    14         }
    15 
    16         protected override void OnSessionStarted()
    17         {
    18             Console.WriteLine("Session已启动");
    19             base.OnSessionStarted();
    20         }
    21 
    22         protected override void OnInit()
    23         {
    24             this.Charset = Encoding.GetEncoding("gb2312");
    25             base.OnInit();
    26         }
    27 
    28         protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
    29         {
    30             Console.WriteLine("遇到未知的请求");
    31             base.HandleUnknownRequest(requestInfo);
    32         }
    33     }
    34 }

      (3)新建一个SocketServer类,继承自AppServer

     1 using SuperSocket.SocketBase;
     2 using System;
     3 using SuperSocket.SocketBase.Config;
     4 
     5 namespace SuperSocketBlog
     6 {
     7     public class SocketServer : AppServer<SocketSession>
     8     {
     9         protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
    10         {
    11             Console.WriteLine("正在准备配置文件");
    12             return base.Setup(rootConfig, config);
    13         }
    14 
    15         protected override void OnStarted()
    16         {
    17             Console.WriteLine("服务已开始");
    18             base.OnStarted();
    19         }
    20 
    21         protected override void OnStopped()
    22         {
    23             Console.WriteLine("服务已停止");
    24             base.OnStopped();
    25         }
    26         protected override void OnNewSessionConnected(SocketSession session)
    27         {
    28             Console.WriteLine("新的连接地址为" + session.LocalEndPoint.Address.ToString() + ",时间为" + DateTime.Now);
    29             base.OnNewSessionConnected(session);
    30         }
    31     }
    32 }

      (4)在配置文件中进行配置,配置后的代码如下:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine" />
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
      </configSections>
      <!--配置SocketServer路径-->
      <superSocket>
        <servers>
          <server name="MySocket" textEncoding="gb2312"
                  serverType="SuperSocketBlog.SocketServer, SuperSocketBlog"
                 ip="Any" port="2018" maxConnectionNumber="100">
          </server>
        </servers>
      </superSocket>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
        </startup>
    </configuration>

      说明:server节点的serverType的属性值第一个是SocketServer的位置,第二个是程序集的名称。

      (5)添加命令类Apply,继承自CommandBase

     1 using SuperSocket.SocketBase.Command;
     2 using SuperSocket.SocketBase.Protocol;
     3 using System;
     4 
     5 namespace SuperSocketBlog
     6 {
     7     public class Apply:CommandBase<SocketSession,StringRequestInfo>
     8     {
     9         public override void ExecuteCommand(SocketSession session, StringRequestInfo requestInfo)
    10         {
    11             //根据参数个数或者其他条件判断,来进行一些自己的操作
    12             if (requestInfo.Parameters.Length==2)
    13             {
    14                 Console.WriteLine("调用成功");
    15                 session.Send("已经成功接收到你的请求
    ");
    16             }
    17             else
    18             {
    19                 session.Send("参数不正确
    ");
    20             }
    21         }
    22     }
    23 }

    (6)在Program.cs文件中对Socket进行初始化

     1             #region 初始化Socket
     2             IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();
     3             if (!bootstrap.Initialize())
     4             {
     5                 Console.WriteLine(DateTime.Now + ":Socket初始化失败
    ");
     6                 return;
     7             }
     8 
     9             var result = bootstrap.Start();
    10             foreach (var server in bootstrap.AppServers)
    11             {
    12                 if (server.State == ServerState.Running)
    13                 {
    14                     Console.WriteLine(DateTime.Now + ":serverName为:" + server.Name + "Socket运行中
    ");
    15                     Console.Read();
    16                 }
    17                 else
    18                 {
    19                     Console.WriteLine(DateTime.Now + ":serverName为:" + server.Name + "Socket启动失败
    ");
    20                 }
    21             }
    22             #endregion

    四、测试

      (1)初始化界面

      (2)打开SocketTool软件,新建一个客户端,连接的端口号(2018)要和上面配置文件中设置的端口号一致。

    (3)点击连接按钮效果图

    (4)使用Apply命令效果图

    说明:(1)发送请求时中间用空格隔开,默认第一个参数为命令名称(和刚才建立的命令类Apply要一致),后面的是需要传递的参数。

      (2)使用SocketTool软件发送请求的时候,要按回车,再点击发送,服务器端才可以接收到。

    问题:(1)如果需求场景变为:可以接收json字符串或者命令(不限制命令名称)格式。则该程序如果接收到Json字符串或者除Apply之外的命令,就需要在SocketSession类里面的

    HandleUnknownRequest方法里进行处理。
    (2)如果不限定命令名称,统一对发送的信息进行处理该怎么写呢?

    写在后面的话:SuperSocket只是会简单的连接,发信息,其实对原理还有更深层的编程不熟悉,还需要再进行深层次的探索。忽然发现好像每一篇文章的最后都有类似的话语,每一个都研究的不深入,只是皮毛而已呢(捂脸)。

  • 相关阅读:
    hadoop常用命令详细解释
    2019-05-20 Sublime Text 编辑
    2019-05-20 什么是分布式系统、分布式锁
    2019-05-19 centos7下删掉一个目录下所有的文件
    2019-05-17 ABRT has detected 1 problem(s). For more info run: abrt-cli list --since 1558053651
    2019-05-17 java.net.BindException: Address already in use: JVM_Bind <null>:8083
    2019-05-16mysql忘记密码怎么办
    2019-05-16查看MySQL版本sql语句
    2019-05-15 cenots7动态IP地址改为静态
    2019-05-14 MySQL通过dos命令操作数据库
  • 原文地址:https://www.cnblogs.com/jas0203/p/9951220.html
Copyright © 2011-2022 走看看