这是根据我自己学习的经历整理出来的,如有不对之处,还请多多指教!

SuperSocket源码下载  

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学习笔记(一)的更多相关文章

  1. SuperSocket学习笔记(二)

    上一篇博客SuperSocket学习笔记(一)说明了怎么快速搭建一个服务器端,这篇文章我想深挖一下SuperSocket 1. 每一个客户端连接到服务器端时,服务器端会将客户端的信息保存到一个Sess ...

  2. SuperSocket学习笔记(一)-一个完整的例子

    一.什么是SuperSocket 以下是作者的介绍 执行以下命令,获取SuperSocket项目 $ git clone https://github.com/kerryjiang/SuperSock ...

  3. SuperSocket 学习笔记-客户端

    客户端: 定义 private AsyncTcpSession client; 初始化 client = new AsyncTcpSession(); client.Connected += Clie ...

  4. js学习笔记:webpack基础入门(一)

    之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...

  5. PHP-自定义模板-学习笔记

    1.  开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2.  整体架构图 ...

  6. PHP-会员登录与注册例子解析-学习笔记

    1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...

  7. 2014年暑假c#学习笔记目录

    2014年暑假c#学习笔记 一.C#编程基础 1. c#编程基础之枚举 2. c#编程基础之函数可变参数 3. c#编程基础之字符串基础 4. c#编程基础之字符串函数 5.c#编程基础之ref.ou ...

  8. JAVA GUI编程学习笔记目录

    2014年暑假JAVA GUI编程学习笔记目录 1.JAVA之GUI编程概述 2.JAVA之GUI编程布局 3.JAVA之GUI编程Frame窗口 4.JAVA之GUI编程事件监听机制 5.JAVA之 ...

  9. seaJs学习笔记2 – seaJs组建库的使用

    原文地址:seaJs学习笔记2 – seaJs组建库的使用 我觉得学习新东西并不是会使用它就够了的,会使用仅仅代表你看懂了,理解了,二不代表你深入了,彻悟了它的精髓. 所以不断的学习将是源源不断. 最 ...

随机推荐

  1. winform 获取当前项目所在的路径

    代码: string curAppPath = System.IO.Directory.GetParent(System.Environment.CurrentDirectory).Parent.Fu ...

  2. <display:column>属性解释

    参考官方网站:http://www.displaytag.org/1.2/displaytag/tagreference.html 所有属性: autolink,class,comparator,de ...

  3. (原)torch的训练过程

    转载请注明出处: http://www.cnblogs.com/darkknightzh/p/6221622.html 参考网址: http://ju.outofmemory.cn/entry/284 ...

  4. 一步步学会使用SeaJS(转)

    原文出处:一步步学会使用SeaJS 2.0 本文分为以下8步,熟悉之后就能够熟练使用SeaJS,从此之后你的生活会变得更加轻松愉悦! 1.SeaJS是什么? 2.下载并检阅SeaJS 3.建立工程和各 ...

  5. 作业:汽车查询--弹窗显示详情,批量删除 ajax做法(0521)

    作业:显示以下界面: 作业要求: 1.查看详细信息,以弹窗的形式显示,使用ajax2.批量删除 一.主页面 <!DOCTYPE html PUBLIC "-//W3C//DTD XHT ...

  6. PHP扩展开发(6) - VS2012下strncasecmp和fopen函数warning

    1. fopen   warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s i ...

  7. Spark学习笔记--stage和task的划分

    https://github.com/JerryLead/SparkInternals/blob/master/markdown/3-JobPhysicalPlan.md stage 和 task 的 ...

  8. 《VIM-Adventures攻略》前言

    本文已转至http://cn.abnerchou.me/2014/03/02/bfdaadb0/ 自从有了计算机,人们就想向其灌输自己的想法. 要想对其输入,自然离不开文本编辑器. 公告:<VI ...

  9. Android从相册中获取图片以及路径

    首先是相册图片的获取: private final String IMAGE_TYPE = "image/*"; private final int IMAGE_CODE = 0; ...

  10. Qt调用VC++生成的动态链接库

    Qt如何调用VC++生成的动态链接库?假设当前有VC++编译器生成的动态库文件testdll.h,testdll.lib和testdll.dll. testdll.h文件源码如下: #ifdef TE ...