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组建库的使用 我觉得学习新东西并不是会使用它就够了的,会使用仅仅代表你看懂了,理解了,二不代表你深入了,彻悟了它的精髓. 所以不断的学习将是源源不断. 最 ...
随机推荐
- XML中 添加或修改时 xmlns="" 怎么删除
//创建节点时 记得加上 ---> xmldoc.DocumentElement.NamespaceURI XmlElement url = xmldoc.CreateElement(&quo ...
- 关于Discuz!nt论坛编辑器图片上传bug,flash域的问题
正在整discuz!nt,现在没有什么人弄了把? 上个星期突然来了个bug,搞死我了,论坛图片不能上传,上传卡在100%没反应了,于是我发现ajax发送到AttachUpload.cs时queryst ...
- WPF合并资源字典
1.合并多个外部资源字典成为本地字典 示例代码 <Page.Resources> <ResourceDictionary> <ResourceDictionary.Mer ...
- 《第一行代码》学习笔记38-服务Service(5)
1.希望服务一旦启动就立刻去执行某个动作,可以将逻辑写在onStartCommand()方法里. 2.onCreate()和onStartCommand()的区别:onCreate()方法是在服务第一 ...
- UILable / UITextField / UIButton
// 获取屏幕大小的view UIView *contentView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]; // ...
- ios app开发步骤
虽然开发一个app的任务看上去可能很艰巨,但是整个过程可以抽象成几个相对简单的步骤,下面这些步骤会在你开发第一个app时帮你步入正途. 定义Concept 每个好app都是从一个concept开始. ...
- C#Mysql数据库爆破源码
声明: 代码仅供学习参考使用!开启了一个子线程,进行爆破! 速度不是很快,代码不是很规范,希望大牛不要喷我! c#控制台程序,需要引用MySql.Data.dll 默认用户名: root密码字典: p ...
- 在sublime text 3中安装中文支持
1.安装package control 使用control+~打开终端,然后输入以下内容并确定: import urllib.request,os;pf='Package Control.subli ...
- 扩展编写jquery插件的方法
比如要扩展验证功能(jquery.validate.js)中的 messages: { required: "This field is required.", remote: & ...
- localhost 与 127.0.0.1 的区别
localhost与127.0.0.1的区别是什么?相信有人会说是本地ip,曾有人说,用127.0.0.1比localhost好,可以减少一次解析.看来这个入门问题还有人不清楚,其实这两者是有区别的. ...