Fork me on GitHub

SuperSocket 1.5 Documentation译文 12 ----- 连接过滤器

SuperSocket中连接过滤器(Connection Filter)是用与对客户端连接进行过滤的接口。通过连接过滤器, 你可以允许或者禁止指定来源的客户端对服务器进行连接。

连接过滤器Connection Filter接口:

/// <summary>
/// 默认连接过滤器
/// </summary>
public interface IConnectionFilter
{
    /// <summary>
    /// 初始化连接过滤器
    /// </summary>
    /// <param name="name">名称</param>
    /// <param name="appServer">服务端对象</param>
    /// <returns></returns>
    bool Initialize(string name, IAppServer appServer);

    /// <summary>
    /// 获取过滤器的名称
    /// </summary>
    string Name { get; }

    /// <summary>
    /// 是否允许根据远程端点的连接
    /// </summary>
    /// <param name="remoteAddress">远程端点.</param>
    /// <returns></returns>
    bool AllowConnect(IPEndPoint remoteAddress);
}

bool Initialize(string name, IAppServer appServer);

此方法用于初始化连接过滤器, name是Filter的名称, options是配置文件中此connection filter元素的属性。

string Name {get;}

返回Filter名称

bool AllowConnect (IPEndPoint remoteAddress);

此方法需要实现通过客户端的endpoint来判断是否允许连接服务器。

下面是一个实现了只允许来自某些IP地址段的客户端的连接的连接过滤器:

public class IPConnectionFilter : IConnectionFilter
{
    private Tuple<long, long>[] m_IpRanges;

    public bool Initialize(string name, IAppServer appServer)
    {
        Name = name;

        var ipRange = appServer.Config.Options.GetValue("ipRange");

        string[] ipRangeArray;

        if (string.IsNullOrEmpty(ipRange)
            || (ipRangeArray = ipRange.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)).Length <= 0)
        {
            throw new ArgumentException("The ipRange doesn't exist in configuration!");
        }

        m_IpRanges = new Tuple<long, long>[ipRangeArray.Length];

        for (int i = 0; i < ipRangeArray.Length; i++)
        {
            var range = ipRangeArray[i];
            m_IpRanges[i] = GenerateIpRange(range);
        }

        return true;
    }

    private Tuple<long, long> GenerateIpRange(string range)
    {
        var ipArray = range.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

        if(ipArray.Length != 2)
            throw new ArgumentException("Invalid ipRange exist in configuration!");

        return new Tuple<long, long>(ConvertIpToLong(ipArray[0]), ConvertIpToLong(ipArray[1]));
    }

    private long ConvertIpToLong(string ip)
    {
        var points = ip.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

        if(points.Length != 4)
            throw new ArgumentException("Invalid ipRange exist in configuration!");

        long value = 0;
        long unit = 1;

        for (int i = points.Length - 1; i >= 0; i--)
        {
            value += unit * points[i].ToInt32();
            unit *= 256;
        }

        return value;
    }

    public string Name { get; private set; }

    public bool AllowConnect(IPEndPoint remoteAddress)
    {
        var ip = remoteAddress.Address.ToString();
        var ipValue = ConvertIpToLong(ip);

        for (var i = 0; i < m_IpRanges.Length; i++)
        {
            var range = m_IpRanges[i];

            if (ipValue > range.Item2)
                return false;

            if (ipValue < range.Item1)
                return false;
        }

        return true;
    }
}

然后你需要更新配置文件来使用这个连接过滤器:

1) 添加配置节点 "connectionFilters";

<connectionFilters>
  <add name="IpRangeFilter"
       type="SuperSocket.QuickStart.ConnectionFilter.IPConnectionFilter, SuperSocket.QuickStart.ConnectionFilter" />
</connectionFilters>

2) 添加服务实例属性;

<server name="EchoServer"
        serverTypeName="EchoService" ip="Any" port="2012"
        connectionFilter="IpRangeFilter"
        ipRange="127.0.1.0-127.0.1.255">
</server>

3) 最终配置应该是这样;

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/>
    </configSections>
    <appSettings>
        <add key="ServiceName" value="EchoService"/>
    </appSettings>
    <superSocket>
        <servers>
            <server name="EchoServer"
                serverTypeName="EchoService"
                ip="Any" port="2012"
                connectionFilter="IpRangeFilter"
                ipRange="127.0.1.0-127.0.1.255">
            </server>
        </servers>
       <serverTypes>
           <add name="EchoService"
                type="SuperSocket.QuickStart.EchoService.EchoServer, SuperSocket.QuickStart.EchoService" />
       </serverTypes>
       <connectionFilters>
           <add name="IpRangeFilter"
                type="SuperSocket.QuickStart.ConnectionFilter.IPConnectionFilter, SuperSocket.QuickStart.ConnectionFilter" />
       </connectionFilters>
    </superSocket>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
    </startup>
</configuration>
posted @ 2013-04-02 22:59  逗豆豆  阅读(399)  评论(0编辑  收藏  举报