How to solve Socket Accept Timeout

Viewed 81

I have a power on-off device to control. If the device is connected to the network, my code works fine. I remove the device from the network on purpose to test it as if the device malfunctions (like power off). And I find out that the System hangs.

I trace that the socket.accept does not execute - 'accept is ok' is not written to a log file. ex.message does not write as well.

My purpose is to send a message to support if there is any device malfunction.

    Using gSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        WriteLog("Start. ")
        Dim remoteSocket As Socket
        
        Try
            gSocket.SendTimeout = 5000
            gSocket.ReceiveTimeout = 5000
            gSocket.Bind(vEndPoint) ' vEndpoint is the local machine
            WriteLog("bind is ok. ")
            gSocket.Listen(10)
            WriteLog("listen is ok. ")
            remoteSocket = gSocket.Accept
            WriteLog("accept is ok. ")


        Catch ex As Exception
            WriteLog(ex.Message)
            
        Finally

        End Try

How can I solve this?

1 Answers

I use BeginAccept to solve it.

            Dim acceptResult As IAsyncResult = gSocket.BeginAccept(Nothing, Nothing)
            Dim Success As Boolean = acceptResult.AsyncWaitHandle.WaitOne(vTimeout, True)
            If Success Then
                remoteSocket = gSocket.EndAccept(acceptResult)
                WriteLog("beginaccept is ok. ")
            Else
                gSocket.Close()                   
                WriteLog("beginaccept failed. ")                    
            End If
Related