6 Replies - 556 Views - Last Post: 05 December 2014 - 03:20 PM Rate Topic: ***-- 2 Votes

#1 Rixterz   User is offline

  • D.I.C Head

Reputation: -7
  • View blog
  • Posts: 163
  • Joined: 26-August 12

I just can't get threads to work properly

Posted 05 December 2014 - 02:03 PM

Hello,

I'm making an application which is supposed to try to connect to my server, and when it has, stop trying to connect.
When it loses the connection to the server, it should try to reconnect on a timer tick.
To test this, I open the client and server. I let the client connect and the server tells me it has done so.
Then I close the server, and the client tells me it's disconnected.
Then I restart the server. I find that the server does not tell me about any connections being made.
The problem I'm having is that although timer.Enabled returns True, no connection is being attempted.
Please try to find the problem below.
Imports System.IO, System.Net, System.Net.Sockets
Imports System.Threading

Public Class Form1

    Dim client As TcpClient

    Dim sWriter As StreamWriter

    Delegate Sub _crossthreadOperation(ByVal doWhat As String)

    Private Sub crossthreadOperation(ByVal doWhat As String)

        On Error Resume Next

        If InvokeRequired Then

            Invoke(New _crossthreadOperation(AddressOf crossthreadOperation), doWhat)

        Else

            If doWhat = "timerStart" Then

                connectTimer.Start()

            ElseIf doWhat = "timerStop" Then

                connectTimer.Stop()

            ElseIf doWhat = "connectionProcedure" Then

                Dim hostname As IPHostEntry = Dns.GetHostEntry("ServerAddressHere")

                Dim ip As IPAddress() = hostname.AddressList

                client = New TcpClient(ip(0).ToString(), 24975)

                client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf receiveData), Nothing)

            End If

        End If

    End Sub

    Private Sub connect()

        Try

            crossthreadOperation("timerStop")

            crossthreadOperation("connectionProcedure")

        Catch ex As Exception

            'can't connect. wait for next tick

            crossthreadOperation("timerStart")

        End Try

    End Sub

    Private Sub disconnect(reconnect As Boolean)

        Try

            client.Client.Close()

            client = Nothing

            If reconnect = True Then

                connectTimer.Start()

            End If

        Catch ex As Exception

            'haven't connected; can't disconnect

        End Try

    End Sub

    Private Sub receiveData(ByVal ar As IAsyncResult)

        Try

            Dim data As String = New StreamReader(client.GetStream).ReadLine

            client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf receiveData, Nothing)

        Catch ex As Exception

            'disconnected; try to reconnect

            disconnect(True)

            Exit Sub

        End Try

    End Sub

    Private Sub sendData(ByVal data As String)

        Try

            sWriter = New StreamWriter(client.GetStream)

            With sWriter

                .WriteLine(data)

                .Flush()

            End With

        Catch ex As Exception

            'problem sending data; restart connection

            disconnect(True)

        End Try

    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

        If e.CloseReason = CloseReason.WindowsShutDown Then

            disconnect(False)

        Else

            e.Cancel = True

        End If

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        connectTimer.Start()

    End Sub

    Private Sub connectTimer_Tick(sender As Object, e As EventArgs) Handles connectTimer.Tick

        t = New Thread(AddressOf connector)

        t.Start()

    End Sub

    Dim t As Thread

    Private Sub connector()

        connect()

    End Sub

End Class



I've tried for hours to successfully debug this to no effect.

-Rixterz

This post has been edited by Rixterz: 05 December 2014 - 02:04 PM


Is This A Good Question/Topic? 0
  • +

Replies To: I just can't get threads to work properly

#2 _HAWK_   User is offline

  • Master(Of Foo)
  • member icon

Reputation: 1162
  • View blog
  • Posts: 4,444
  • Joined: 02-July 08

Re: I just can't get threads to work properly

Posted 05 December 2014 - 02:32 PM

Stop using On Error Resume Next. There is some redundancy with calling connector(), just to call connect(), just use connect() instead. So there any error being thrown? What happens when you follow the code during debug?
Was This Post Helpful? 0
  • +
  • -

#3 Rixterz   User is offline

  • D.I.C Head

Reputation: -7
  • View blog
  • Posts: 163
  • Joined: 26-August 12

Re: I just can't get threads to work properly

Posted 05 December 2014 - 02:45 PM

View Post_HAWK_, on 05 December 2014 - 02:32 PM, said:

Stop using On Error Resume Next. There is some redundancy with calling connector(), just to call connect(), just use connect() instead. So there any error being thrown? What happens when you follow the code during debug?


I am now directly calling "connect()" in the timer tick event.

New code section:

 Private Sub connect()

        Try

            connectTimer.Stop()

            Dim hostname As IPHostEntry = Dns.GetHostEntry("uca1.ddns.net")

            Dim ip As IPAddress() = hostname.AddressList

            client = New TcpClient(ip(0).ToString(), 24975)

            client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf receiveData), Nothing)

        Catch ex As Exception

            'can't connect. wait for next tick

            MsgBox("Can't connect: " & ex.Message)

            connectTimer.Start()

        End Try

    End Sub



If the server is not running, the UI freezes. After about 20 seconds (connection timeout), the msgbox shows with the "connection refused" error, but I cannot click "OK" to close it. The application then becomes useless and I have to close it.

I need the UI to stay fully responsive throughout being disconnected, connected and disconnecting

-Rixterz

This post has been edited by Rixterz: 05 December 2014 - 02:56 PM

Was This Post Helpful? 0
  • +
  • -

#4 Rixterz   User is offline

  • D.I.C Head

Reputation: -7
  • View blog
  • Posts: 163
  • Joined: 26-August 12

Re: I just can't get threads to work properly

Posted 05 December 2014 - 03:02 PM

Bump. I desperately need to finish this as I can't do anything else with my project whatsoever
Was This Post Helpful? 0
  • +
  • -

#5 _HAWK_   User is offline

  • Master(Of Foo)
  • member icon

Reputation: 1162
  • View blog
  • Posts: 4,444
  • Joined: 02-July 08

Re: I just can't get threads to work properly

Posted 05 December 2014 - 03:09 PM

That is not what I meant, call it with the t = New Thread(AddressOf Connect) part. When it refuses connection is it still trying to run in a loop? Maybe consider having a button that says 'Connect' and only trying to connect once with an attempt when there is an obvious connection refusal happening. You also may be behind a port forwarding issue being on a computer that is hooked to a wireless router.
Was This Post Helpful? 0
  • +
  • -

#6 Rixterz   User is offline

  • D.I.C Head

Reputation: -7
  • View blog
  • Posts: 163
  • Joined: 26-August 12

Re: I just can't get threads to work properly

Posted 05 December 2014 - 03:13 PM

View Post_HAWK_, on 05 December 2014 - 03:09 PM, said:

That is not what I meant, call it with the t = New Thread(AddressOf Connect) part. When it refuses connection is it still trying to run in a loop? Maybe consider having a button that says 'Connect' and only trying to connect once with an attempt when there is an obvious connection refusal happening. You also may be behind a port forwarding issue being on a computer that is hooked to a wireless router.


Portforwarding is working fine. Re-read my question to see the process I took to prove it.
Even with using t = New Thread(AddressOf Connect), the second connection is not made. The timer must be running, as msgbox(timer.enabled) = true

This post has been edited by Rixterz: 05 December 2014 - 03:15 PM

Was This Post Helpful? 0
  • +
  • -

#7 Rixterz   User is offline

  • D.I.C Head

Reputation: -7
  • View blog
  • Posts: 163
  • Joined: 26-August 12

Re: I just can't get threads to work properly

Posted 05 December 2014 - 03:20 PM

Solved it. The starting/stopping of the timer was being done within t so illegal crossthread calls were made. I added a delegate, did the invoking business and it works great now.

Thanks for taking an interest

-Rixterz
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1