首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我需要帮助建立一个TCP连接,使用VB.net来优先考虑速度。

我需要帮助建立一个TCP连接,使用VB.net来优先考虑速度。
EN

Stack Overflow用户
提问于 2022-10-27 22:10:02
回答 1查看 37关注 0票数 0

我有一个高速控制应用程序。由于选择的设备,我们被迫使用TCP创建套接字。这是我的第一个VB.net应用,我有点挣扎。

该设备最终连接,但我目前正在测试的8个设备中的一个。启动程序只需大约5分钟,之后似乎运行良好。

到目前为止我的情况是这样的。我循环遍历并将IPAddresses数组设置为字符串。我将设备状态初始化为-1 (没有通信)。创建一个设置所有套接字的循环,尝试连接到TCP客户端。在这里使用try和catch设置设备状态并验证哪些连接正在工作。对不起,如果格式化不好,这是我第一次在堆栈溢出上发帖。我已经找了好几天的答案了,压力很大。

代码语言:javascript
复制
代码语言:javascript
复制
 ' set the server address to the correct device auto increment for the devices and append the string
        For index = 0 To 7
' put this variable in here because it wont let me append a double to a string
            Dim String_index As String = index + 1
            ServerAddress(index) = "XXX.XXX.X.10" & String_index
        Next
        For index = 0 To 7
            DeviceStat(index) = -1
        Next
        ' create a new sending socket
        tcp_SendSocket = New TcpClient
        For i = 0 To 7
            Try
                ' connect the socket
                tcp_SendSocket.Connect(ServerAddress(i), 7000)
                If tcp_SendSocket.Connected = True Then
                    DeviceStat(i) = 1
                End If

            Catch ex As Exception
                'MessageBox.Show("Ethernet not available. Check network connections.")
                If tcp_SendSocket.Connected = False Then
                    DeviceStat(i) = -1
                End If
            End Try
        Next
代码语言:javascript
复制
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-31 15:36:39

我想我解决了这个问题。更好的方法是将try放在for循环中,原因是它给了我一个更好的调试窗口,在这里我可以查看每个连接期间发生的事情。原来tcpclient正在为我的其他设备计时,而我连接的设备是在2ms内连接的,所以一旦我进入工厂测试它,它就不会有任何问题。代码也稍微干净一些。

代码语言:javascript
复制
 ' set the device ip address array up, this might be an extra step since we turn it into ip address instance and set up device status
    For index = 0 To 7
        Dim String_index As String = index + 1
        ServerAddress(index) = "XXX.XXX.X.10" & String_index
        DeviceStat(index) = -1
    Next

    ' set up the ip addresses as IP address instances instead of strings
    Dim ipAddresses(7) As System.Net.IPAddress
    For i = 0 To (ServerAddress.Length - 1)
        ipAddresses(i) = IPAddress.Parse(ServerAddress(i))
    Next

    'Set up multiple send sockets
    tcp_SendSocket = New TcpClient(AddressFamily.InterNetwork)

    'Connect the socket to each device in ipAddresses
    For i = 0 To 7
        Try
            tcp_SendSocket.Connect(ipAddresses(i), 7000)
        Catch ex As Exception

        End Try
        If tcp_SendSocket.Connected = False Then
            DeviceStat(i) = -1
        ElseIf tcp_SendSocket.Connected = True Then
            DeviceStat(i) = 1
        End If
    Next
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74228817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档