当前位置: 代码网 > it编程>编程语言>C# > C#处理TCP数据的方法详解

C#处理TCP数据的方法详解

2024年07月03日 C# 我要评论
前言tcp是一个面向连接的流数据传输协议,用人话说就是传输是一个已经建立好连接的管道,数据都在管道里像流水一样流淌到对端。那么数据必然存在几个问题,比如数据如何持续的读取,数据包的边界等。nagle&

前言

tcp是一个面向连接的流数据传输协议,用人话说就是传输是一个已经建立好连接的管道,数据都在管道里像流水一样流淌到对端。

那么数据必然存在几个问题,比如数据如何持续的读取,数据包的边界等。

nagle's算法

nagle 算法的核心思想是,在一个 tcp 连接上,最多只能有一个未被确认的小数据包(小于 mss,即最大报文段大小)

优势

减少网络拥塞:通过合并小数据包,减少了网络中的数据包数量,降低了拥塞的可能性。

提高网络效率:在低速网络中,nagle 算法可以显著提高传输效率。

劣势

增加延迟:在交互式应用中,nagle 算法可能导致显著的延迟,因为它等待 ack 或合并数据包。

c#中如何配置?

var _socket = new socket(ipaddress.any.addressfamily, sockettype.stream, protocoltype.tcp);
_serversocket.nodelay = _options.nodelay;

连接超时

在调用客户端socket连接服务器的时候,可以设置连接超时机制,具体可以传入一个任务的取消令牌,并且设置超时时间。

cancellationtokensource connecttokensource = new cancellationtokensource();
connecttokensource.cancelafter(3000); //3秒
await _socket.connectasync(remoteendpoint, connecttokensource.token);

ssl加密传输

tcp使用ssl加密传输,通过非对称加密的方式,利用证书,保证双方使用了安全的密钥加密了报文。在c#中如何配置?

服务端配置

//创建证书对象
var _certificate  = _certificate = new x509certificate2(_options.pfxcertfilename, _options.pfxpassword);
 
//与客户端进行验证
if (allowinguntrustedsslcertificate) //是否允许不受信任的证书
{
    sslstream = new sslstream(networkstream, false,
        (obj, certificate, chain, error) => true);
}
else
{
    sslstream = new sslstream(networkstream, false);
}
 
try
{
    //servercertificate:用于对服务器进行身份验证的 x509certificate
    //clientcertificaterequired:一个 boolean 值,指定客户端是否必须为身份验证提供证书
    //checkcertificaterevocation:一个 boolean 值,指定在身份验证过程中是否检查证书吊销列表
    await sslstream.authenticateasserverasync(new sslserverauthenticationoptions()
    {
        servercertificate = x509certificate,
        clientcertificaterequired = mutuallyauthenticate,
        certificaterevocationcheckmode = checkcertificaterevocation ? x509revocationmode.online : x509revocationmode.nocheck
    }, cancellationtoken).configureawait(false);
 
    if (!sslstream.isencrypted || !sslstream.isauthenticated)
    {
        return false;
    }
 
    if (mutuallyauthenticate && !sslstream.ismutuallyauthenticated)
    {
        return false;
    }
}
catch (exception)
{
    throw;
}
 
//完成验证后,通过sslstream传输数据
int readcount = await sslstream.readasync(buffer, _lifecycletokensource.token)
    .configureawait(false);

客户端配置

var _certificate = new x509certificate2(_options.pfxcertfilename, _options.pfxpassword);
 
if (_options.isssl) //如果使用ssl加密传输
{
    if (_options.allowinguntrustedsslcertificate)//是否允许不受信任的证书
    {
        _sslstream = new sslstream(_networkstream, false,
                (obj, certificate, chain, error) => true);
    }
    else
    {
        _sslstream = new sslstream(_networkstream, false);
    }
 
    _sslstream.readtimeout = _options.readtimeout;
    _sslstream.writetimeout = _options.writetimeout;
    await _sslstream.authenticateasclientasync(new sslclientauthenticationoptions()
    {
        targethost = remoteendpoint.address.tostring(),
        enabledsslprotocols = system.security.authentication.sslprotocols.tls12,
        certificaterevocationcheckmode = _options.checkcertificaterevocation ? x509revocationmode.online : x509revocationmode.nocheck,
        clientcertificates = new x509certificatecollection() { _certificate }
    }, connecttokensource.token).configureawait(false);
 
    if (!_sslstream.isencrypted || !_sslstream.isauthenticated ||
        (_options.mutuallyauthenticate && !_sslstream.ismutuallyauthenticated))
    {
        throw new invalidoperationexception("ssl authenticated faild!");
    }
}

keepalive

keepalive不是tcp协议中的,而是各个操作系统本身实现的功能,主要是防止一些socket突然断开后没有被感知到,导致一直浪费资源的情况。

/// <summary>
/// 开启socket的keepalive
/// 设置tcp协议的一些keepalive参数
/// </summary>
/// <param name="socket"></param>
/// <param name="tcpkeepaliveinterval">没有接收到对方确认,继续发送keepalive的发送频率</param>
/// <param name="tcpkeepalivetime">keepalive的空闲时长,或者说每次正常发送心跳的周期</param>
/// <param name="tcpkeepaliveretrycount">keepalive之后设置最大允许发送保活探测包的次数,到达此次数后直接放弃尝试,并关闭连接</param>
internal static void setkeepalive(this socket socket, int tcpkeepaliveinterval, int tcpkeepalivetime, int tcpkeepaliveretrycount)
{
    socket.setsocketoption(socketoptionlevel.socket, socketoptionname.keepalive, true);
    socket.setsocketoption(socketoptionlevel.tcp, socketoptionname.tcpkeepaliveinterval, tcpkeepaliveinterval);
    socket.setsocketoption(socketoptionlevel.tcp, socketoptionname.tcpkeepalivetime, tcpkeepalivetime);
    socket.setsocketoption(socketoptionlevel.tcp, socketoptionname.tcpkeepaliveretrycount, tcpkeepaliveretrycount);
}

具体的开启,还需要看操作系统的版本以及不同操作系统的支持。

粘包断包处理

pipe & readonlysequence

tcp面向应用是流式数据传输,所以接收端接到的数据是像流水一样从管道中传来,每次取到的数据取决于应用设置的缓冲区大小,以及套接字本身缓冲区待读取字节数

c#中提供的pipe就如上图一样,是一个管道pipe有两个对象成员,一个是pipewriter,一个是pipereader,可以理解为一个是生产者,专门往管道里灌输数据流,即字节流,一个是消费者,专门从管道里获取字节流进行处理。

可以看到pipe中的数据包是用链表关联的,但是这个数据包是从socke缓冲区每次取到的数据包,它不一定是一个完整的数据包,所以这些数据包连接起来后形成了一个c#提供的另外一个抽象的对象readonlysequence。

但是这里还是没有提供太好的处理断包和粘包的办法,因为断包粘包的处理需要两方面

1、业务数据包的定义

2、数据流切割出一个个完整的数据包

假设业务已经定义好了数据包,那么我们如何从pipe中这些数据包根据业务定义来从不同的数据包中切割出一个完整的包,那么就需要readonlysequence,它提供的操作方法,非常方便我们去切割数据,主要是头尾数据包的切割。

假设我们业务层定义了一个数据包结构,数据包是不定长的,包体长度每次都写在包头里,我们来实现一个数据包过滤器。

//收到消息
 while (!_receivedatatokensource.token.iscancellationrequested)
 {
     try
     {
        //从pipe中获取缓冲区
         memory<byte> buffer = _pipewriter.getmemory(_options.buffersize);
         int readcount = 0;
         readcount = await _sslstream.readasync(buffer, _lifecycletokensource.token).configureawait(false);
 
         if (readcount > 0)
         {
 
             var data = buffer.slice(0, readcount);
             //告知消费者,往pipe的管道中写入了多少字节数据
             _pipewriter.advance(readcount);
         }
         else
         {
             if (isdisconnect())
             {
                 await disconnectasync();
             }
 
             throw new socketexception();
         }
 
         flushresult result = await _pipewriter.flushasync().configureawait(false);
         if (result.iscompleted)
         {
             break;
         }
     }
     catch (ioexception)
     {
         //todo log
         break;
     }
     catch (socketexception)
     {
         //todo log
         break;
     }
     catch (taskcanceledexception)
     {
         //todo log
         break;
     }
 }
 
 _pipewriter.complete();
//消费者处理数据
 while (!_lifecycletokensource.token.iscancellationrequested)
 {
     readresult result = await _pipereader.readasync();
     readonlysequence<byte> buffer = result.buffer;
     readonlysequence<byte> data;
     do
     {
        //通过过滤器得到一个完整的包
         data = _receivepackagefilter.resolvepackage(ref buffer);
 
         if (!data.isempty)
         {
             onreceiveddata?.invoke(this, new clientdatareceiveeventargs(data.toarray()));
         }
     }
     while (!data.isempty && buffer.length > 0);
     _pipereader.advanceto(buffer.start);
 }
 
 _pipereader.complete();
/// <summary>
/// 解析数据包
/// 固定报文头解析协议
/// </summary>
/// <param name="headersize">数据报文头的大小</param>
/// <param name="bodylengthindex">数据包大小在报文头中的位置</param>
/// <param name="bodylengthbytes">数据包大小在报文头中的长度</param>
/// <param name="islittleendian">数据报文大小端。windows中通常是小端,unix通常是大端模式</param>
/// </summary>
/// <param name="sequence">一个完整的业务数据包</param>
public override readonlysequence<byte> resolvepackage(ref readonlysequence<byte> sequence)
{
    var len = sequence.length;
    if (len < _bodylengthindex) return default;
    var bodylengthsequence = sequence.slice(_bodylengthindex, _bodylengthbytes);
    byte[] bodylengthbytes = arraypool<byte>.shared.rent(_bodylengthbytes);
    try
    {
        int index = 0;
        foreach (var item in bodylengthsequence)
        {
            array.copy(item.toarray(), 0, bodylengthbytes, index, item.length);
            index += item.length;
        }
 
        long bodylength = 0;
        int offset = 0;
        if (!_islittleendian)
        {
            offset = bodylengthbytes.length - 1;
            foreach (var bytes in bodylengthbytes)
            {
                bodylength += bytes << (offset * 8);
                offset--;
            }
        }
        else
        {
 
            foreach (var bytes in bodylengthbytes)
            {
                bodylength += bytes << (offset * 8);
                offset++;
            }
        }
 
        if (sequence.length < _headersize + bodylength)
            return default;
 
        var endposition = sequence.getposition(_headersize + bodylength);
        var data = sequence.slice(0, endposition);//得到完整数据包
        sequence = sequence.slice(endposition);//缓冲区中去除取到的完整包
 
        return data;
    }
    finally
    {
        arraypool<byte>.shared.return(bodylengthbytes);
    }
}

以上就是实现了固定数据包头实现粘包断包处理的部分代码。

关于tcp的连接还有一些,比如客户端连接限制,空闲连接关闭等。

到此这篇关于c#处理tcp数据的方法详解的文章就介绍到这了,更多相关c#处理tcp数据内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com