Search code examples
vb.nettcpclient

Accessing TcpClient in VB.net DLL


I'm writing a DLL for SimTools that accesses the telemetry data of NoLimitsRollercoasterSimulator. The TcpClient is created during loading the DLL with

Dim tcpClientNLS As New TcpClient()

The tcpClientNLS can then be accessed by all the different subroutines in the DLL. When I create the TcpClient in one of the subroutines (e.g. Public Sub GameStart() ) the client is only accessible in this subroutine (GameStart). The issues is that when the NoLimits simulation ends, the DLL-subsoutine GameStop must close the TcpClient, otherwise the NoLimits simulation hangs.

Because the tcpClientNLS.Close() call not only closes the connetcion but also disposes the tcpClient, it is no longer accessible. So the next time the NoLimits simulation starts and the DLL-GameStart routine tries to connect the TcpClient with tcpClientNLS.Connect("127.0.0.1", 15151) it throws an exception. I have tried several different options - so far with no luck.

  • Is it possible to create a new TcpClient within a subroutine (e.g. DLL-GameStart) and access it in another subroutine (e.g. DLL-GameStop)?
  • I can also create a new TcpClient in the DLL-Process_Telemetry subroutine everytime I read the telemetry data from the NoLimits Simulation and close the TcpClient right after (100× per sec) in the same DLL-Process_Telemetry subroutine. But I guess this just consumes a lot of processing time?
  • Is there another way to close the connection and reuse the TcpClient?

Thank you for your help in advance!


Solution

  • Is it possible to create a new TcpClient within a subroutine (e.g. DLL-GameStart) and access it in another subroutine (e.g. DLL-GameStop)?

    It's not possible to create a new variable within a method/subroutine and then access it from the outside,

    BUT you can always reinstantiate your global tcpClientNLS variable whenever you like, for example in your GameStart() method:

    Dim tcpClientNLS As TcpClient
    
    Public Sub GameStart()
        tcpClientNLS = New TcpClient()
        tcpClientNLS.Connect("127.0.0.1", 15151)
        ...
    End Sub
    

    I can also create a new TcpClient in the DLL-Process_Telemetry subroutine everytime I read the telemetry data from the NoLimits Simulation and close the TcpClient right after (100× per sec) in the same DLL-Process_Telemetry subroutine. But I guess this just consumes a lot of processing time?

    Doing so can potentially slow things down, yes.

    Is there another way to close the connection and reuse the TcpClient?

    You can always reinstantiate it (like shown above) right after the tcpClientNLS.Close() call too.