SuperSocket学习笔记(一)

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

SuperSocket源码下载  

SuperSocket文档

安装并启动Telnet

学习方法:

  QuickStrart + 文档

参考资料:

  服务器架设:
   http://blog.csdn.net/kuanzai123/article/details/17013213

  基本认识:
       http://blog.qiangk.com/2013/08/03/learning-supersocket-opensouce-project.html

下面是一个例子的主要源码:

最终形成的目录:(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 "01"; }
}
/// <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[1024];
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(2012)) //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 = 1;

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 > 0)
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[1];

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[1];

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[0], 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学习笔记(一),布布扣,bubuko.com

时间: 2024-08-03 14:39:06

SuperSocket学习笔记(一)的相关文章

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

一.什么是SuperSocket 以下是作者的介绍 执行以下命令,获取SuperSocket项目 $ git clone https://github.com/kerryjiang/SuperSocket 二.项目结构 三.开发过程 1.新建一个控制台项目ConsoleApp 1.1引用相关项目 1.2从Solution Items中引进日志文件 1.3设置SuperSocket.SocketBase45的log4net文件属性设置为[复制到本地] 2.编写Main方法 1 using Syst

SuperSocket框架学习笔记4-SuperWebSocket---使用SubCommandBase

首先下载所需要的 DLL http://download.csdn.net/detail/wai2dance123/7389285 或者参见第2章  到SuperSocket官网下载 http://www.cnblogs.com/xmcrew/p/3747354.html 1,新建一个 .NET4.0 控制台应用程序 命名为 DiyServers 添加以下引用 将默认的Program.cs改名为  DiyServers.cs 并添加以下命名空间 2,写自己的DSession和DServer继承自

SuperSocket框架学习笔记3-构建Unity3D__WebSocket4Net客户端程序

确保上一节服务器程序运行没有问题,否则请仔细看上一节 新建一个Unity3D项目(我的Unity3D版本是4.2.0) 1,在Unity3D内新建一个文件夹命名 Plugin 将下载的 客户端: WebSocket4Net  客户端必备 http://websocket4net.codeplex.com/ WebSocket4Net.dll   这个DLL复制到 Unity3D里面刚才新建的 Plugin文件夹内(注意Unity不得使用中文) ----------- 查看Unity下面的状态面板

SuperSocket框架学习笔记1-启动服务器

SuperSocket 是一个轻量级的可扩展的 Socket 开发框架,可用来构建一个服务器端 Socket 程序,而无需了解如何使用 Socket,如何维护Socket连接,Socket是如何工作的.该项目使用纯 C# 开发,易于扩展和集成到已有的项目.只要你的已有系统是使用.NET开发的,你都能够使用 SuperSocket来轻易的开发出你需要的Socket应用程序来集成到你的现有系统之中. 下载地址:http://www.supersocket.net/ 1,新建一个控制台应用程序,.NE

SuperSocket框架学习笔记2-构建SuperWebSocket服务器程序

SuperSocket框架学习笔记2-构建SuperWebSocket服务器程序 上一节简单介绍了 基本的SuperSocket服务器 这一节我们使用 SuperWebSocket构建一个 能与Unity3D通信的(Console控制台)服务器程序 嘎嘎 先下载   需要的  DLL类库 服务端: SuperSocket1.6.1 这个必备 http://www.supersocket.net/ SuperWebSocket 服务端必备 http://superwebsocket.codeple

vector 学习笔记

vector 使用练习: /**************************************** * File Name: vector.cpp * Author: sky0917 * Created Time: 2014年04月27日 11:07:33 ****************************************/ #include <iostream> #include <vector> using namespace std; int main

Caliburn.Micro学习笔记(一)----引导类和命名匹配规则

Caliburn.Micro学习笔记(一)----引导类和命名匹配规则 用了几天时间看了一下开源框架Caliburn.Micro 这是他源码的地址http://caliburnmicro.codeplex.com/ 文档也写的很详细,自己在看它的文档和代码时写了一些demo和笔记,还有它实现的原理记录一下 学习Caliburn.Micro要有MEF和MVVM的基础 先说一下他的命名规则和引导类 以后我会把Caliburn.Micro的 Actions IResult,IHandle ICondu

jQuery学习笔记(一):入门

jQuery学习笔记(一):入门 一.JQuery是什么 JQuery是什么?始终是萦绕在我心中的一个问题: 借鉴网上同学们的总结,可以从以下几个方面观察. 不使用JQuery时获取DOM文本的操作如下: 1 document.getElementById('info').value = 'Hello World!'; 使用JQuery时获取DOM文本操作如下: 1 $('#info').val('Hello World!'); 嗯,可以看出,使用JQuery的优势之一是可以使代码更加简练,使开

[原创]java WEB学习笔记93:Hibernate学习之路---Hibernate 缓存介绍,缓存级别,使用二级缓存的情况,二级缓存的架构集合缓存,二级缓存的并发策略,实现步骤,集合缓存,查询缓存,时间戳缓存

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好者,互联网技术发烧友 微博:伊直都在0221 QQ:951226918 -----------------------------------------------------------------------------------------------------------------