我正在開發一個高速控制應用程式。由于選擇的設備,我們被迫使用 TCP 來創建套接字。這是我的第一個 VB.net 應用程式,我有點掙扎。
該設備最終會連接,但我目前正在使用 8 臺設備中的 1 臺進行測驗。啟動程式大約需要 5 分鐘,之后似乎運行正常。
這是我到目前為止所擁有的。我遍歷并將一組 IPAddresses 設定為字串。我將設備狀態初始化為 -1(無通信)。創建一個回圈來設定所有套接字,嘗試連接到 TCP 客戶端。在此處使用 try and catch 設定設備狀態并驗證哪些連接正在作業。抱歉,如果格式不正確,這是我第一次在堆疊溢位上發帖。幾天來我一直在尋找答案并為此感到壓力。
' 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
uj5u.com熱心網友回復:
我想我弄清楚了這個問題。更好的做法是將 try 放在 for 回圈中,原因是它給了我一個更好的除錯視窗,我可以在其中查看每個連接期間發生的情況。事實證明,我的其他設備的 tcpclient 超時,而我連接的設備在 2 毫秒內連接,所以一旦我進入工廠測驗它,它應該沒有任何問題。代碼也稍微干凈一些。
' 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524254.html
