I have a high speed controls application I'm working on. Due to the devices chosen, we are forced to use TCP to create sockets. This is my first VB.net app and I'm struggling a little bit.
The device eventually connects but I'm currently testing with 1 of the 8 devices. It takes about 5 minutes just to start the program, and seems to run okay after that.
Here's what I have so far. I loop through and set an array of IPAddresses as strings. I initialize the device status to -1 (No communication). Create a loop to set up all the sockets, try connecting to the TCP client. Using a try and catch here to set the device status and verify which connections are working. Sorry if this is formatted poorly, this is my first time posting on stack overflow. I've been looking for an answer for multiple days and stressing over it.
' 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
CodePudding user response:
I think I figured out the issue. The better thing to do was put the try inside the for loop, the reason is it gave me a better debugging window, where I could view what was happening during each connection. Turns out that the tcpclient was timing out for my other devices, while the device I do have hooked up was connecting in 2ms, so once I get into factory testing it, it shouldn't have any issues. Also slightly cleaner code.
' 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