SuperSocket学习笔记(一)
这是根据我自己学习的经历整理出来的,如有不对之处,还请多多指教!
安装并启动Telnet
学习方法:
QuickStrart + 文档
参考资料:
下面是一个例子的主要源码:
最终形成的目录:(Config文件夹中log4net.config文件来自SupertSocket源码)

文件源码:
app.config
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<runtime>
<gcServer enabled="true" />
</runtime>
</configuration>
ControlCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using SuperSocket.SocketBase; namespace ConsoleApp
{
public class ControlCommand
{
public string Name { get; set; } public string Description { get; set; } public Func<IBootstrap, string[], bool> Handler { get; set; }
}
}
HELLO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol; namespace ConsoleApp
{
/// <summary>
/// 自定义命令类HELLO,继承CommandBase,并传入自定义连接类MySession
/// </summary>
public class HELLO : CommandBase<MySession, StringRequestInfo>
{
/// <summary>
/// 命令编号
/// </summary>
public override string Name
{
get { return ""; }
}
/// <summary>
/// 自定义执行命令方法,注意传入的变量session类型为MySession
/// </summary>
/// <param name="session"></param>
/// <param name="requestInfo"></param>
public override void ExecuteCommand(MySession session, StringRequestInfo requestInfo)
{
session.Send("\r\nHello World!");
}
}
}
MyServer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using SuperSocket.SocketBase; namespace ConsoleApp
{
/// <summary>
/// 自定义服务器类MyServer,继承AppServer,并传入自定义连接类MySession
/// </summary>
public class MyServer : AppServer<MySession>
{
protected override void OnStartup()
{
base.OnStarted();
Console.WriteLine("服务器已启动");
} /// <summary>
/// 输出新连接信息
/// </summary>
/// <param name="session"></param>
protected override void OnNewSessionConnected(MySession session)
{
base.OnNewSessionConnected(session);
Console.Write("\r\n" + session.LocalEndPoint.Address.ToString() + ":连接");
} /// <summary>
/// 输出断开连接信息
/// </summary>
/// <param name="session"></param>
/// <param name="reason"></param>
protected override void OnSessionClosed(MySession session, CloseReason reason)
{
base.OnSessionClosed(session, reason);
Console.Write("\r\n" + session.LocalEndPoint.Address.ToString() + ":断开连接");
} protected override void OnStopped()
{
base.OnStopped();
Console.WriteLine("服务器已停止");
} }
}
MySession.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol; namespace ConsoleApp
{
/// <summary>
/// 自定义连接类MySession,继承AppSession,并传入到AppSession
/// </summary>
public class MySession : AppSession<MySession>
{
/// <summary>
/// 新连接
/// </summary>
protected override void OnSessionStarted()
{
Console.WriteLine(this.LocalEndPoint.Address.ToString()); //输出客户端IP地址
this.Send("\r\nHello User");
} /// <summary>
/// 未知的Command
/// </summary>
/// <param name="requestInfo"></param>
protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
{
this.Send("\r\n未知的命令");
} /// <summary>
/// 捕捉异常并输出
/// </summary>
/// <param name="e"></param>
protected override void HandleException(Exception e)
{
this.Send("\r\n异常: {0}", e.Message);
} /// <summary>
/// 连接关闭
/// </summary>
/// <param name="reason"></param>
protected override void OnSessionClosed(CloseReason reason)
{
base.OnSessionClosed(reason);
} }
}
Program.cs
注:不好意思,这个里面有一些没用的代码,留着是因为以后可能要用到
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase.Command;
using MyAppSession;
using ConsoleApp;
using System.Net;
using System.Net.Sockets;
using SuperSocket.SocketEngine; namespace ConsoleApp
{
class Program
{
private static byte[] data = new byte[];
static void Main(string[] args)
{
Console.WriteLine("Press any key to start the server!"); Console.ReadKey();
Console.WriteLine(); //var appServer = new AppServer();
var appServer = new MyServer(); //Setup the appServer
if (!appServer.Setup()) //Setup with listening port 建立一个服务器,端口是2012
{
Console.WriteLine("Failed to setup!");
Console.ReadKey();
return;
} Console.WriteLine(); //Try to start the appServer
if (!appServer.Start()) //服务器启动
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
} #region 客户端连接成功之后进行的操作
#region 1.处理连接
appServer.NewSessionConnected += new SessionHandler<MySession>(appServer_NewSessionConnected);
#endregion 1.处理连接 //#region 2.处理请求
////appServer.NewRequestReceived += new RequestHandler<AppSession, StringRequestInfo>(appServer_NewRequestReceived);
//appServer.NewRequestReceived += new RequestHandler<AppSession, StringRequestInfo>(appServer_NewRequestReceived);
//#endregion 2.处理请求
//appServer.NewRequestReceived += new RequestHandler<MySession, StringRequestInfo>(ExecuteCommand);
#endregion 客户端连接成功之后进行的操作 Console.WriteLine("The server started successfully, press key 'q' to stop it!"); #region 测试命令添加
//RegisterCommands();
#endregion 测试命令添加 while (true)
{
var str = Console.ReadLine();
if (str.ToLower().Equals("exit"))
{
break;
}
}
Console.WriteLine(); //while (Console.ReadKey().KeyChar != 'q')
//{
// Console.WriteLine();
// continue;
//} ////Stop the appServer
//appServer.Stop(); //服务器关闭 Console.WriteLine("服务已停止,按任意键退出!");
Console.ReadKey();
}
#region 事件
/// <summary>
/// 连接事件
/// </summary>
/// <param name="session"></param>
static void appServer_NewSessionConnected(MySession session)
{
session.Send("Welcome to SuperSocket Telnet Server");
}
/// <summary>
/// 请求
/// </summary>
/// <param name="session"></param>
/// <param name="requestInfo"></param>
static void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
{
switch (requestInfo.Key.ToUpper())
{
case ("ECHO"):
session.Send(requestInfo.Body);
break; case ("ADD"): //加法
session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
break; case ("MULT"): //乘法 var result = ; foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))
{
result *= factor;
} session.Send(result.ToString());
break;
}
}
#endregion 事件 //#region 方法
///// <summary>
///// 输出输入内容
///// </summary>
//public class ECHO : CommandBase<AppSession, StringRequestInfo>
//{
// public override string Name
// {
// get { return "01"; }
// }
// public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo)
// {
// session.Send(requestInfo.Body);
// }
//}
///// <summary>
///// 定义一个名为"ADD"的类去处理Key为"ADD"的请求
///// </summary>
//public class ADD : CommandBase<AppSession, StringRequestInfo>
//{
// public override string Name
// {
// get { return "02"; }
// }
// public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo)
// {
// session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
// }
//}
///// <summary>
///// 定义一个名为"MULT"的类去处理Key为"MULT"的请求
///// </summary>
//public class MULT : CommandBase<AppSession, StringRequestInfo>
//{
// public override string Name
// {
// get { return "03"; }
// }
// public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo)
// {
// var result = 1; // foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))
// {
// result *= factor;
// } // session.Send(result.ToString());
// }
//}
//#endregion 方法 #region 使用SuperSocket自带事件处理方式
private static Dictionary<string, ControlCommand> m_CommandHandlers = new Dictionary<string, ControlCommand>(StringComparer.OrdinalIgnoreCase); private static void AddCommand(string name, string description, Func<IBootstrap, string[], bool> handler)
{
var command = new ControlCommand
{
Name = name,
Description = description,
Handler = handler
}; m_CommandHandlers.Add(command.Name, command);
} private static void RegisterCommands()
{
AddCommand("List", "List all server instances", ListCommand);
AddCommand("Start", "Start a server instance: Start {ServerName}", StartCommand);
AddCommand("Stop", "Stop a server instance: Stop {ServerName}", StopCommand);
} static bool ListCommand(IBootstrap bootstrap, string[] arguments)
{
foreach (var s in bootstrap.AppServers)
{
var processInfo = s as IProcessServer; if (processInfo != null && processInfo.ProcessId > )
Console.WriteLine("{0}[PID:{1}] - {2}", s.Name, processInfo.ProcessId, s.State);
else
Console.WriteLine("{0} - {1}", s.Name, s.State);
} return false;
} static bool StopCommand(IBootstrap bootstrap, string[] arguments)
{
var name = arguments[]; if (string.IsNullOrEmpty(name))
{
Console.WriteLine("Server name is required!");
return false;
} var server = bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (server == null)
{
Console.WriteLine("The server was not found!");
return false;
} server.Stop(); return true;
} static bool StartCommand(IBootstrap bootstrap, string[] arguments)
{
var name = arguments[]; if (string.IsNullOrEmpty(name))
{
Console.WriteLine("Server name is required!");
return false;
} var server = bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (server == null)
{
Console.WriteLine("The server was not found!");
return false;
} server.Start(); return true;
} static void ReadConsoleCommand(IBootstrap bootstrap)
{
var line = Console.ReadLine(); if (string.IsNullOrEmpty(line))
{
ReadConsoleCommand(bootstrap);
return;
} if ("quit".Equals(line, StringComparison.OrdinalIgnoreCase))
return; var cmdArray = line.Split(' '); ControlCommand cmd; if (!m_CommandHandlers.TryGetValue(cmdArray[], out cmd))
{
Console.WriteLine("Unknown command");
ReadConsoleCommand(bootstrap);
return;
} try
{
if (cmd.Handler(bootstrap, cmdArray))
Console.WriteLine("Ok");
}
catch (Exception e)
{
Console.WriteLine("Failed. " + e.Message + Environment.NewLine + e.StackTrace);
} ReadConsoleCommand(bootstrap);
}
#endregion 使用SuperSocket自带事件处理方式 }
}
效果:
服务器端:

telnet端:命令是01

注意:如果不使用telnet,则记得在客户端发送命令的末尾加上"\r\n",因为SuperSocket默认的协议是命令行协议
这是一个很简单的例子,虽然只是一小步,但也给我带来了前进的动力,自勉一下,呵呵!!!
SuperSocket学习笔记(一)的更多相关文章
- SuperSocket学习笔记(二)
上一篇博客SuperSocket学习笔记(一)说明了怎么快速搭建一个服务器端,这篇文章我想深挖一下SuperSocket 1. 每一个客户端连接到服务器端时,服务器端会将客户端的信息保存到一个Sess ...
- SuperSocket学习笔记(一)-一个完整的例子
一.什么是SuperSocket 以下是作者的介绍 执行以下命令,获取SuperSocket项目 $ git clone https://github.com/kerryjiang/SuperSock ...
- SuperSocket 学习笔记-客户端
客户端: 定义 private AsyncTcpSession client; 初始化 client = new AsyncTcpSession(); client.Connected += Clie ...
- js学习笔记:webpack基础入门(一)
之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...
- PHP-自定义模板-学习笔记
1. 开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2. 整体架构图 ...
- PHP-会员登录与注册例子解析-学习笔记
1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...
- 2014年暑假c#学习笔记目录
2014年暑假c#学习笔记 一.C#编程基础 1. c#编程基础之枚举 2. c#编程基础之函数可变参数 3. c#编程基础之字符串基础 4. c#编程基础之字符串函数 5.c#编程基础之ref.ou ...
- JAVA GUI编程学习笔记目录
2014年暑假JAVA GUI编程学习笔记目录 1.JAVA之GUI编程概述 2.JAVA之GUI编程布局 3.JAVA之GUI编程Frame窗口 4.JAVA之GUI编程事件监听机制 5.JAVA之 ...
- seaJs学习笔记2 – seaJs组建库的使用
原文地址:seaJs学习笔记2 – seaJs组建库的使用 我觉得学习新东西并不是会使用它就够了的,会使用仅仅代表你看懂了,理解了,二不代表你深入了,彻悟了它的精髓. 所以不断的学习将是源源不断. 最 ...
随机推荐
- .NET程序集签名
强命名程序集的一个好处是防篡改.假如我有一个程序集MyDll.dll,如果我用我自己的私钥进行签名将程序集中的内容进行哈希处理,其他人如果不知道我的私钥的话,就不能篡改我的这个程序集进行某些恶意的行为 ...
- WPF 获取屏幕分辨率(获取最大宽高)等
double x = SystemParameters.WorkArea.Width;//得到屏幕工作区域宽度 double y = SystemParameters.WorkArea.Height; ...
- ArrayList 练习
ArrayList list = new ArrayList(); Random rd = new Random(); ; i <; i++) { , ); //是否包含当前数字 if (!li ...
- 使用 Nginx 来反向代理多个 NoderCMS
Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器.Nginx是由Igor Sysoev为俄罗斯访问量第二的R ...
- ECSTORE2.0 下载 (变量标签)
条目 用途 备注 coupon.mc.use_times 优惠券可用次数 - security.guest.enabled 是否支持非会员购物 - site.version version的最后修改时 ...
- Python入门-----介绍
摘要:Python语言的特点 ----->优雅.明确.简单 一.Python适合的领域 web网站和各种网络服务 系统工具和脚本 作为“胶水”语言,把其他语言开发的模块包装起来方便使用 二.Py ...
- map关联容器
#include<map> map<k, v> m; 创建一个名为 m 的空 map 对象,其键和值的类型分别为 k 和 v map<k, v>m(m2);创建 m ...
- commons-pool2-中的一些配置
/** * 连接失效检测相关 */ // 空闲时进行连接测试,会启动异步evi ...
- Activiti 使用自己的身份认证服务
Activiti 中内置了用户和组管理的服务,由identityService 提供调用接口,默认在spring配置中如下: <bean id="identityService&quo ...
- 通过JCONSOLE监控TOMCAT的JVM使用情况
这个也是要学入一下,JVMr 虚拟机原理不可少. 参考配置URL“: http://blog.163.com/kangle0925@126/blog/static/277581982011527723 ...