简体   繁体   English

发送最佳实践

[英]Socket.Send best practise

I'm attempting to improve some of our networking code, and here I need to use Socket.Send . 我正在尝试改善一些网络代码,在这里我需要使用Socket.Send

However, MSDN states that it's the developers own responsibility to handle retries, and since the Socket.Send method won't necessary send all data in a single request (depends on buffer size), I've decided to go with following loop: 但是,MSDN声明处理重试是开发人员的责任,并且由于Socket.Send方法不必在单个请求中发送所有数据(取决于缓冲区大小),因此我决定采用以下循环:

try
{
    int timeout = TimeSpan.FromSeconds(10).Milliseconds;
    int waitTime = TimeSpan.FromMilliseconds(30).Milliseconds;

    Socket socket = tcpClient.Client;
    socket.SendTimeout = timeout ;

    int offset = 0;

    while (offset != data.Length)
    {
        if (socket.Poll(waitTime , SelectMode.SelectWrite))
        {
            offset += socket.Send(data, offset, data.Length - offset, SocketFlags.None);
        }
    }
}
catch (SocketException)
{
    tcpClient.Close();
}

However, I'm uncertain regarding the offset, as it's zero based, which probably would result in the offset missing a single byte on every loop here, or am I wrong? 但是,我不确定偏移量,因为它是从零开始的,这可能会导致偏移量在这里的每个循环中都丢失一个字节,还是我错了?

Also, are there any other best practises to be concerned about here? 另外,这里还有其他最佳做法需要关注吗?

The MSDN Article says: MSDN文章说:

Return Value Type: System.Int32 The number of bytes sent to the Socket. 返回值类型:System Int32发送到套接字的字节数。

So I wouldn't worry about it. 所以我不用担心。 My only advice for best practises is to consider using WCF, and it is a lot easier to use and much more reliable than sockets in .NET, especially for anything complex. 我对最佳做法的唯一建议是考虑使用WCF,它比.NET中的套接字更容易使用且更可靠,尤其是对于任何复杂的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM