Home:ALL Converter>My program can't read an ASCII string from TCP connection, keeps looping

My program can't read an ASCII string from TCP connection, keeps looping

Ask Time:2018-06-08T21:55:40         Author:Alexis Robin

Json Formatter

I'm connecting to a specific TCP port of a server, do stuff, and I need to disconnect at some point, then wait for the server to open its port again and reconnect.

My program loops forever.

To disconnect from the server, I sent from the server the string "TCP:OFF" and the close the port (server side). Whenever my program reads this line, I want it to close its connection and wait the server to open its port again. This is because of the TCP/IP protocol.

The problem is that the specific ASCII string sent from my server is not read until I put my mouse over my window (weird). At the end, I want my program to work by itself and minimized, without human intervention.

There must be a problem in the timing of my networkStream reading.


While tcpClient.Connected() = False
            tcpClient.ReceiveTimeout = 1000
            tcpClient.SendTimeout = 1000
            tcpClient.Connect("", 10003)
            Console.WriteLine("Connection OK")
        Catch ex As Exception
            Console.WriteLine("ERRORR : Server unreachable")
        End Try
    End While

Dim networkStream As NetworkStream = tcpClient.GetStream()

If networkStream.CanRead And networkStream.DataAvailable Then
            ReadData = ""
            Dim myReadBuffer As Byte() = New Byte(7) {}
            Dim numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length)
            ReadData = Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)
            Console.Write(ReadData & vbCrLf)
        Catch ex As Exception
            Console.Write("Error reading data")
        End Try
    End If

    If ReadData = "TCP:OFF" Then
        ReadData = ""
        Console.WriteLine("Closing connection")
        tcpClient = New TcpClient
    End If

I'm doing a Windows form program in latest Visual Studio.

Author:Alexis Robin,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50762253/my-program-cant-read-an-ascii-string-from-tcp-connection-keeps-looping