博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
FastSocket
阅读量:7234 次
发布时间:2019-06-29

本文共 7384 字,大约阅读时间需要 24 分钟。

hot3.png

FastSocket是一个轻量级易扩展的c#异步socket通信库,项目开始于2011年,经过近3年不断调整与改进,目前在功能和性能上均有不错的表现。

项目地址: 

在Nuget官方源中搜索fastsocket可快速安装引用

QQ群:257612438

FastSocket内置了命令行、二进制、thrift协议,基于此开发了Zookeeper, Redis, Thrift等c#异步客户端,接下来将会一一公开。

Requirements

.Net 4.0 or Mono 2.6

Projects using FastSocket.Net

Example Usage

1: 简单的命令行服务

新建控制台项目,添加FastSocket.SocketBase,FastSocket.Server引用

自定义服务实现MyService

/// /// 实现自定义服务/// public class MyService : CommandSocketService
{    /// 
    /// 当连接时会调用此方法    ///     /// 
    public override void OnConnected(IConnection connection)    {        base.OnConnected(connection);        Console.WriteLine(connection.RemoteEndPoint.ToString() + " connected");        connection.BeginSend(PacketBuilder.ToCommandLine("welcome"));    }    /// 
    /// 当连接断开时会调用此方法    ///     /// 
    /// 
    public override void OnDisconnected(IConnection connection, Exception ex)    {        base.OnDisconnected(connection, ex);        Console.ForegroundColor = ConsoleColor.Red;        Console.WriteLine(connection.RemoteEndPoint.ToString() + " disconnected");        Console.ForegroundColor = ConsoleColor.Gray;    }    /// 
    /// 当发生错误时会调用此方法    ///     /// 
    /// 
    public override void OnException(IConnection connection, Exception ex)    {        base.OnException(connection, ex);        Console.WriteLine("error: " + ex.ToString());    }    /// 
    /// 处理未知命令    ///     /// 
    /// 
    protected override void HandleUnKnowCommand(IConnection connection, StringCommandInfo commandInfo)    {        commandInfo.Reply(connection, "unknow command:" + commandInfo.CmdName);    }}

Exit命令

/// /// 退出命令/// public sealed class ExitCommand : ICommand
{    /// 
    /// 返回命令名称    ///     public string Name    {        get { return "exit"; }    }    /// 
    /// 执行命令    ///     /// 
    /// 
    public void ExecuteCommand(IConnection connection, StringCommandInfo commandInfo)    {        connection.BeginDisconnect();//断开连接    }}

App.config配置

  
    
  
  
    
      
    
  

初始化及启动服务

static void Main(string[] args){    SocketServerManager.Init();    SocketServerManager.Start();    Console.ReadLine();}

启动服务,然后在cmd中运行telnet 127.0.0.1 8400, 运行截图如下:

其中welcome中当连接建立时服务端发送到终端的。

connection.BeginSend(PacketBuilder.ToCommandLine("welcome"));

unknow command:Hello是因为没有对应的"Hello"命令实现由HandleUnKnowCommand输出的

protected override void HandleUnKnowCommand(IConnection connection, StringCommandInfo commandInfo){    commandInfo.Reply(connection, "unknow command:" + commandInfo.CmdName);}

当在终端中键入exit时,触发了ExitCommand.ExecuteCommand方法,服务端主动断开连接,终端退出。

2: 在服务中使用自定义二进制协议

新建控制台项目,命名为Server

添加FastSocket.SocketBase,FastSocket.Server引用

Socket命令服务类: Sodao.FastSocket.Server.CommandSocketService泛型类

其中需要实现Socket连接,断开,异常,发送完回调及处理未知命令的方法

内置的二进制命令对象: Sodao.FatSocket.Server.Command.AsyncBinaryCommandInfo

由一个command name,一个唯一标识SeqId和主题内容buffer构建。

定义服务类MyService继承CommandSocketService类,

泛型类型为上述的AsyncBinanryCommandInfo

/// /// 实现自定义服务/// public class MyService : CommandSocketService
{    /// 
    /// 当连接时会调用此方法    ///     /// 
    public override void OnConnected(IConnection connection)    {        base.OnConnected(connection);        Console.WriteLine(connection.RemoteEndPoint.ToString() + " connected");    }    /// 
    /// 当连接断开时会调用此方法    ///     /// 
    /// 
    public override void OnDisconnected(IConnection connection, Exception ex)    {        base.OnDisconnected(connection, ex);        Console.ForegroundColor = ConsoleColor.Red;        Console.WriteLine(connection.RemoteEndPoint.ToString() + " disconnected");        Console.ForegroundColor = ConsoleColor.Gray;    }    /// 
    /// 当发生错误时会调用此方法    ///     /// 
    /// 
    public override void OnException(IConnection connection, Exception ex)    {        base.OnException(connection, ex);        Console.WriteLine("error: " + ex.ToString());    }    /// 
    /// 当服务端发送Packet完毕会调用此方法    ///     /// 
    /// 
    public override void OnSendCallback(IConnection connection, SendCallbackEventArgs e)    {        base.OnSendCallback(connection, e);        Console.ForegroundColor = ConsoleColor.Green;        Console.WriteLine("send " + e.Status.ToString());        Console.ForegroundColor = ConsoleColor.Gray;    }    /// 
    /// 处理未知的命令    ///     /// 
    /// 
    protected override void HandleUnKnowCommand(IConnection connection, AsyncBinaryCommandInfo commandInfo)    {        Console.WriteLine("unknow command: " + commandInfo.CmdName);    }}

实现一个命令如示例项目中的SumCommand类,命令类需要实现ICommand泛型接口

即服务中可以进行处理的服务契约

而泛型类型即上述的AsyncBinaryCommandInfo

/// /// sum command/// 用于将一组int32数字求和并返回/// public sealed class SumCommand : ICommand
{    /// 
    /// 返回服务名称    ///     public string Name    {        get { return "sum"; }    }    /// 
    /// 执行命令并返回结果    ///     /// 
    /// 
    public void ExecuteCommand(IConnection connection, AsyncBinaryCommandInfo commandInfo)    {        if (commandInfo.Buffer == null || commandInfo.Buffer.Length == 0)        {            Console.WriteLine("sum参数为空");            connection.BeginDisconnect();            return;        }        if (commandInfo.Buffer.Length % 4 != 0)        {            Console.WriteLine("sum参数错误");            connection.BeginDisconnect();            return;        }        int skip = 0;        var arr = new int[commandInfo.Buffer.Length / 4];        for (int i = 0, l = arr.Length; i < l; i++)        {            arr[i] = BitConverter.ToInt32(commandInfo.Buffer, skip);            skip += 4;        }        commandInfo.Reply(connection, BitConverter.GetBytes(arr.Sum()));    }}

app.config

  
    
  
  
    
      
    
  

其中section name="socketServer" 为服务端默认读取的sectionName

type为反射自FastSocket.Server中的config类型

server配置中,name自定,serviceType为上述实现的服务类反射类型

协议名为asyncBinary

在Main函数中启动服务

static void Main(string[] args){    SocketServerManager.Init();    SocketServerManager.Start();    Console.ReadLine();}

新建控制台应用程序,命名为Client

添加FastSocket.Client,FastSocket.SocketBase引用

客户端的代码为组织命令向服务端请求

创建一个Sodao.FastSocket.Client.AsyncBinarySocketClient的实例

并通过RegisterServerNode来注册服务端节点,需要注意name必须唯一

并且地址为我们服务端运行的地址,端口为服务端配置文件中配置的端口号

static void Main(string[] args){    var client = new Sodao.FastSocket.Client.AsyncBinarySocketClient(8192, 8192, 3000, 3000);    //注册服务器节点,这里可注册多个(name不能重复)    client.RegisterServerNode("127.0.0.1:8401", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8401));    //client.RegisterServerNode("127.0.0.1:8402", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.2"), 8401));    //组织sum参数, 格式为<
>    //这里的参数其实也可以使用thrift, protobuf, bson, json等进行序列化,    byte[] bytes = null;    using (var ms = new System.IO.MemoryStream())    {        for (int i = 1; i <= 1000; i++) ms.Write(BitConverter.GetBytes(i), 0, 4);        bytes = ms.ToArray();    }    //发送sum命令    client.Send("sum", bytes, res => BitConverter.ToInt32(res.Buffer, 0)).ContinueWith(c =>    {        if (c.IsFaulted)        {            Console.WriteLine(c.Exception.ToString());            return;        }        Console.WriteLine(c.Result);    });    Console.ReadLine();}

转载于:https://my.oschina.net/bv10000/blog/311341

你可能感兴趣的文章
paramiko建立无密码传输认证
查看>>
提升编程能力
查看>>
为什么说云计算会在2013年盈利呢?
查看>>
ioremap学习笔记
查看>>
BGP as-path acl拒绝+允许模式
查看>>
haproxy+pacemaker高可用负载均衡
查看>>
ios开发工程师常见面试题汇总
查看>>
Juniper中IS-IS协议介绍
查看>>
我的友情链接
查看>>
谈一谈可能用到数据持久化的地方
查看>>
我的友情链接
查看>>
centos上的时间同步
查看>>
使用mysqladmin命令修改MySQL密码与忘记密码
查看>>
利用fdisk将硬盘剩余空间进行分区
查看>>
解决键盘挡住部分组件 降低用户体验的解决办法
查看>>
开启Cisco交换机DHCP Snooping功能
查看>>
linux中目录的说明小结
查看>>
使用sublime同步编辑线上脚本
查看>>
new和delete
查看>>
Exchange 2010 – NLB Client Access (on Virtual Machines)
查看>>