using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.Common;
using SuperSocket.Facility.Protocol;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketEngine;

namespace OilServer
{
class Program
{
static void Main(string[] args)
{
#region 从配置文件启动
var bootstrap = BootstrapFactory.CreateBootstrap();
if (!bootstrap.Initialize())
{
Console.WriteLine("Failed to initialize!");
Console.ReadKey();
return;
}
var result = bootstrap.Start();

Console.WriteLine("Start result: {0}!", result);

if (result == StartResult.Failed)
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
}

Console.WriteLine("Press key 'q' to stop it!");

while (Console.ReadKey().KeyChar != 'q')
{
Console.WriteLine();
continue;
}

Console.WriteLine();

//Stop the appServer
bootstrap.Stop();

Console.WriteLine("The server was stopped!");
Console.ReadKey();
#endregion
#region 编程启动
//MyServer oilServer=new MyServer();
//oilServer.Setup("127.0.0.1", 9200);
//oilServer.Start();
//Console.WriteLine("输入任意键结束...");
//Console.ReadLine();
//oilServer.Stop();
#endregion
}
}

/// <summary>
/// 某个完整请求
/// </summary>
public class MyRequestInfo: RequestInfo<byte[]>
{
public MyRequestInfo(string key, byte[] body)
: base(key, body)
{

}
}

/// <summary>
/// 请求解析
/// </summary>
public class MyReceiveFilter : FixedHeaderReceiveFilter<MyRequestInfo>
{
public MyReceiveFilter(): base(4)//头部为4个字节
{
}

protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length)
{
int len =
BitConverter.ToInt32(
new byte[] {header[offset + 3],header[offset+2], header[offset + 1], header[offset] }, 0);
return len;
}

protected override MyRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length)
{
var requestInfo= new MyRequestInfo(Guid.NewGuid().ToString(), bodyBuffer.CloneRange(offset, length));
return requestInfo;
}
}
/// <summary>
/// 请求解析工厂
/// </summary>
public class MyReceiveFilterFactory : IReceiveFilterFactory<MyRequestInfo>
{
public IReceiveFilter<MyRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, System.Net.IPEndPoint remoteEndPoint)
{
return new MyReceiveFilter();
}
}

/// <summary>
/// 某个socket会话
/// </summary>
public class MyOilSession : AppSession<MyOilSession, MyRequestInfo>
{
public MyOilSession()
{
this.Charset = System.Text.UTF8Encoding.UTF8;
}
public MyOilClient Client { get; private set; }
protected override void OnSessionStarted()
{
//this.Client.SessionRegiste(this);
base.OnSessionStarted();
}

protected override void OnSessionClosed(CloseReason reason)
{
//add your business operations
//this.Client.SessionUnRegiste(this);
}

protected override void HandleUnknownRequest(MyRequestInfo requestInfo)
{
base.HandleUnknownRequest(requestInfo);
}

protected override void HandleException(Exception e)
{
base.HandleException(e);
}

protected override void OnInit()
{
base.OnInit();
}

public void NewRequestReceived(MyRequestInfo requestInfo)
{
int s = System.Threading.Thread.CurrentThread.GetHashCode();
int k = s;
var requestData = requestInfo.Body;
}
}
public interface IDespatchServer
{
void DispatchMessage(IDespatchServer despatchServer, MyOilSession session, byte[] data);
}
/// <summary>
/// 服务器端
/// </summary>
public class MyServer : AppServer<MyOilSession, MyRequestInfo>,IDespatchServer
{
public MyServer()
: base(new MyReceiveFilterFactory())
{
base.NewSessionConnected += MyOilServer_NewSessionConnected;
base.NewRequestReceived += MyOilServer_NewRequestReceived;
base.SessionClosed += MyOilServer_SessionClosed;
int s = System.Threading.Thread.CurrentThread.GetHashCode();
int k = s;
}

void MyOilServer_SessionClosed(MyOilSession session, CloseReason value)
{
//throw new NotImplementedException();
int s = System.Threading.Thread.CurrentThread.GetHashCode();
int k = s;
}

void MyOilServer_NewRequestReceived(MyOilSession session, MyRequestInfo requestInfo)
{
//throw new NotImplementedException();
session.NewRequestReceived(requestInfo);
int s = System.Threading.Thread.CurrentThread.GetHashCode();
int k = s;
IDespatchServer iserver = null;
switch (this.Name)
{
case "TelnetServerA":
iserver = this.Bootstrap.GetServerByName("TelnetServerB") as IDespatchServer;
break;
case "TelnetServerB":
iserver = this.Bootstrap.GetServerByName("TelnetServerC") as IDespatchServer;
break;
case "TelnetServerC":
iserver = this.Bootstrap.GetServerByName("TelnetServerA") as IDespatchServer;
break;
}
if(iserver!=null)
iserver.DispatchMessage(this, session, requestInfo.Body);
else
{

}
}

void MyOilServer_NewSessionConnected(MyOilSession session)
{
//throw new NotImplementedException();
}

protected override void OnStarted()
{
base.OnStarted();
}
protected override void OnStopped()
{
base.OnStopped();
}

public List<MyOilSession> Find(string loginCode)
{
var sessions = this.GetSessions(a =>a.Client!=null&& a.Client.LoginCode == loginCode);
return sessions.ToList();
}

public void DispatchMessage(IDespatchServer despatchServer, MyOilSession session, byte[] data)
{
var sessions=this.GetAllSessions();
foreach (var myOilSession in sessions)
{
myOilSession.Send(data, 0, data.Length);
}
}
}

public class MyOilClient
{
public string DeviceToken { get; set; }
public string LoginCode { get; set; }
public string OrgCode { get; set; }
public Guid ClientID
{
get;
private set;
}
public MyOilClientManager ClientManager { get; set; }
public MyOilClient(Guid clientID)
{
this.ClientID = clientID;
}
/// <summary>
/// 客户端的所有会话
/// </summary>
private List<MyOilSession> AllSessions = new List<MyOilSession>(1);

public int SessionsCount
{
get
{
lock (AllSessions)
{
return AllSessions.Count;
}
}
}
/// <summary>
/// 添加会话
/// </summary>
/// <param name="session"></param>
public void SessionRegiste(MyOilSession session)
{
lock (AllSessions)
{
if (!AllSessions.Contains(session))
AllSessions.Insert(0,session);
}
}

public void SessionUnRegiste(MyOilSession session)
{
lock (AllSessions)
{
if (AllSessions.Contains(session))
AllSessions.Remove(session);
}
}

public bool Send(byte[] data, int offset, int length)
{
var session = GetEnableSession();
if (session != null)
{
session.Send(data, offset, length);
return true;
}
else
{
return false;
}
}
public MyOilSession GetEnableSession()
{
lock (AllSessions)
{
foreach (var myOilSession in AllSessions)
{
if (myOilSession.Connected)
{
return myOilSession;
}
}
}
return null;
}
}

public class MyOilClientManager
{
private List<MyOilClient> AllClients = new List<MyOilClient>();

public void OilClientRegiste(MyOilClient client)
{
lock (AllClients)
{
if(!AllClients.Contains(client))
AllClients.Add(client);
}
}

public bool OilClientUnRegiste(MyOilClient client)
{
lock (AllClients)
{
if (AllClients.Contains(client))
{
AllClients.Remove(client);
return true;
}
else
{
return false;
}
}
}
}
}

SuperSocket使用demo的更多相关文章

  1. supersocket+controller+action

    public class MasterServer : SuperSocket.SocketBase.AppServer<MasterSession> { } public class M ...

  2. 认识SuperSocket 1.6.4

    SuperSocket 是一个轻量级的可扩展的 Socket 开发框架,由江振宇先生开发,之所以选用它是因为一下几点恰好复合项目需求: 开源,基于Apache 2.0协议,可以免费使用到商业项目. 高 ...

  3. SuperSocket 最基础入门

    ---恢复内容开始--- SuperSocket 是什么? 首先我们明确一下SuperSocket 本质是什么? 网络框架 !  ok , 那么我们直接上上官网,作者已经开源到Github,可以做两件 ...

  4. SUPERSOCKET 客户端

    SUPERSOCKET.CLIENTENGINE 简单使用 2015年5月27日 HYJIACAN 发表回复 阅读 11,105 次 江大没有给ClientEngine的Demo,一直没有找到其它的. ...

  5. 我的第一个Socket程序-SuperSocket使用入门(一)

    第一次使用Socket,遇到过坑,也涨过姿势,网上关于SuperSocket的教程基本都停留在官方给的简单demo上,实际使用还是会碰到一些问题,所以准备写两篇博客,分别来介绍SuperSocket以 ...

  6. NET使用SuperSocket完成TCP/IP通信

    1)为什么使用SuperSocket? 性能高,易上手.有中文文档,我们可以有更多的时间用在业务逻辑上,SuperSocket有效的利用自己的协议解决粘包 2)SuperSocket的协议内容? 命令 ...

  7. c#实例化继承类,必须对被继承类的程序集做引用 .net core Redis分布式缓存客户端实现逻辑分析及示例demo 数据库笔记之索引和事务 centos 7下安装python 3.6笔记 你大波哥~ C#开源框架(转载) JSON C# Class Generator ---由json字符串生成C#实体类的工具

    c#实例化继承类,必须对被继承类的程序集做引用   0x00 问题 类型“Model.NewModel”在未被引用的程序集中定义.必须添加对程序集“Model, Version=1.0.0.0, Cu ...

  8. 通过一个demo了解Redux

    TodoList小demo 效果展示 项目地址 (单向)数据流 数据流是我们的行为与响应的抽象:使用数据流能帮我们明确了行为对应的响应,这和react的状态可预测的思想是不谋而合的. 常见的数据流框架 ...

  9. 很多人很想知道怎么扫一扫二维码就能打开网站,就能添加联系人,就能链接wifi,今天说下这些格式,明天做个demo

    有些功能部分手机不能使用,网站,通讯录,wifi基本上每个手机都可以使用. 在看之前你可以扫一扫下面几个二维码先看看效果: 1.二维码生成 网址 (URL) 包含网址的 二维码生成 是大家平时最常接触 ...

随机推荐

  1. 《wc》-linux命令五分钟系列之十七

    本原创文章属于<Linux大棚>博客,博客地址为http://roclinux.cn.文章作者为rocrocket. 为了防止某些网站的恶性转载,特在每篇文章前加入此信息,还望读者体谅. ...

  2. 用frame实现最基本的上中下三层布局,中间又分左右两部分.

    用frame实现最基本的上中下三层布局,中间又分左右两部分. 用frame的好处在于不用象DIV一样要对浮动和大小进行精确控制,以及要考虑宽屏的时候怎么办.而且在导航的时候非常简单.比如说,左边是导航 ...

  3. JavaScript学习总结【8】、面向对象编程

    1.什么是面向对象编程 要理解面向对象,得先搞清楚什么是对象,首先需要明确一点这里所说的对象,不是生活中的搞男女朋友对象,面向对象就是面向着对象,换在代码中,就是一段代码相中了另一段代码,自此夜以继日 ...

  4. php开源项目学习二次开发的计划

      开源项目: cms 国内 dedecms cmstop 国外 joomla, drupal 电商 国内 ecshop 国外 Magento 论坛 discuz 博客 wordpress   学习时 ...

  5. C# Winform开发框架企业版V4.0新特性

    企业版V4.0 - 新特性 C/S系统开发框架-企业版 V4.0 (Enterprise Edition) 简介: http://www.csframework.com/cs-framework-4. ...

  6. python【第十二篇】Mysql基础

    内容: 1.数据库介绍及MySQL简介 2.MySQL基本操作 1 数据库介绍 1.1什么是数据库? 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库,每个数据库都有一个或多个不同 ...

  7. 前端开发福音!阿里Weex跨平台移动开发工具开源-b

    阿里巴巴今天在Qcon大会上宣布跨平台移动开发工具Weex开放内测邀请.Weex能够完美兼顾性能与动态性,让移动开发者通过简捷的前端语法写出Native级别的性能体验,并支持iOS.安卓.YunOS及 ...

  8. Linux相关命令

    使用的是ubuntu 安装JDK   输入java 命令会有提示安装的软件列表 sudo apt-get install openjdk-6-jdk sudo rm file名 删除文件 sudo r ...

  9. 数据结构练习 00-自测5. Shuffling Machine (20)

    Shuffling is a procedure used to randomize a deck of playing cards. Because standard shuffling techn ...

  10. 欧拉计划 NO05 ps:4题想过,好做,但麻烦,有时间补充,这题也不难!

    问题重述: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without an ...