在 VB.NET 中优化 TCP/IP 套接字实现

Optimize a TCP/IP Socket Implementation in VB.NET

在两台联网计算机之间进行连接时,我有大约 40 毫秒的延迟,我正在尝试找出原因。我怀疑服务器应用程序是原因。我已经使用其他软件(即 Hercules)检查过延迟与我的软件有关,并且我考虑过传输位而不是字符串。拥塞可能不是原因,但可能是缓冲区和数据包大小——考虑我在一些早期 RFC 文档中阅读的内容。我认为延迟是由于服务器而不是客户端造成的,尽管这只是我的猜测。我用 ActionScript 编写了客户端。

我问这个问题是因为谷歌搜索关键字 TCP/IP 和优化 returns 结果是 TCP/IP 配置而不是实现。我是 TCP/IP 编程的新手,所以我希望更高级的程序员可以很容易地发现错误。

服务器应用程序在 VB.NET 中编程:

Public Class Form1

Public Shared remoteAddress As IPAddress = IPAddress.Any
Public Shared port As Int32 = 8080

Public Shared server As New TcpListener(remoteAddress, port)
Public client As TcpClient = Nothing

'....


While (True)
        Try

            Dim buffer(65536) As Byte

            Dim stuff As Integer = client.ReceiveBufferSize
            Console.WriteLine(stuff)

            networkStream.Read(buffer, 0, CInt(client.ReceiveBufferSize))

            Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(buffer)

            dataFromClient = dataFromClient.Substring(dataFromClient.IndexOf("/") + 1, dataFromClient.IndexOf("\") - 1)


            If dataFromClient Like "/END\" Or dataFromClient Like "/STOP\" Then
                Console.WriteLine("STOP REQUESTED")

                Exit While
            End If

            SetMarker(dataFromClient)

            Console.WriteLine(dataFromClient)

            Dim serverResponse As String = "Receiving marker #" + Convert.ToString(requestCount) + ":  " + dataFromClient
            Dim sendBytes As [Byte]() = System.Text.Encoding.ASCII.GetBytes(serverResponse)
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            networkStream.Flush()
            Console.WriteLine(serverResponse)

        Catch illegalSyntax As System.ArgumentException
            Console.WriteLine("ERROR: Use correct syntax: /command\ Example: /S1\, /STOP\")
        Catch socketEx As SocketException
            Console.WriteLine(SocketError.Interrupted)

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

        requestCount = requestCount + 1
    End While

一些想法: 从尽可能小的程序开始,然后衡量性能。慢慢添加功能,当性能达到不可接受的水平时,您就会知道程序的哪一部分花费的时间最多。

为此,您尝试放入一些基本的分析代码以查看花费最多时间的地方,并意识到额外的代码需要额外的时间来处理。

为了做到这一点,或许可以使用Environment.TickCount来测量时间。我认为还有其他一些高性能定时器。

也就是说,我会开始在几个地方寻找:

-您正在一个紧密循环的顶部分配一个数组。为什么不在循环外声明数组,然后清除它,或者更有效地跟踪有多少数组项正在使用,并相应地调整代码。

-通过将字符串变量重新分配回自身,您将导致分配一个全新的字符串。与其重新分配子字符串,不如做一个 String.contains 来检查你的条件

-like是模式匹配关键字。尝试使用相等来测试您的条件。模式匹配比测试相等性更昂贵。

-您正在调用我们没有其定义的名为 SetMarker 的函数。这个函数在做什么?写入数据库或文件?还有什么?也许这个功能很慢。