[RESOLVED] Winsock closing before data gets sent
I have two PCs connected using winsock (TCP), and before one of them disconnects my program sends a message to let the other end know that the connection is being killed. To do this, I have a very simple bit of code:
Code:
Private Sub BtnDisconnect_Click()
If Sock1.State = sckConnected Then
Sock1.SendData ("~disconnecting")
End If
Sock1.Close
End Sub
However, the other computer never receives the message. If I remove "Sock1.Close" it works fine. I don't really have a clue what is happening. Is there any simple way to fix this problem?
Re: Winsock closing before data gets sent
have you tried waiting until the Send_Complete triggers? eg:
Code:
'/// Boolean handler to determine when to disconnect.
Private DC_Sent As Boolean
Private Sub Command1_Click()
DC_Sent = False
'/// connect your socket
End Sub
Private Sub btnDisconnect_Click()
If sock1.State = sckConnected Then
sock1.SendData ("~disconnecting")
DC_Sent = True
End If
End Sub
Private Sub sock1_SendComplete()
If DC_Sent = True Then
sock1.Close
End If
End Sub
Re: Winsock closing before data gets sent
As dynamic said, use the SendComplete() event. I've often written a WaitForSend() sub to help keep things simple if you have a lot of code that sends something before disconnecting.
vb Code:
Option Explicit
'Used so DoEvents is only called when needed.
Private Declare Function GetInputState Lib "user32" () As Long
Private bolSending As Boolean 'Sending data?
Private Sub WaitForSend()
bolSending = True
Do
If GetInputState Then DoEvents
Loop Until Not bolSending Or Winsock1.State = sckClosed Or Winsock1.State = sckError
End Sub
Private Sub Winsock1_SendComplete()
bolSending = False
End Sub
'Then you can use the code like this:
Private Sub cmdSendBeforeClose_Click()
Winsock1.SendData "~disconnecting"
WaitForSend
Winsock1.Close
End Sub
Re: Winsock closing before data gets sent
Thank you both. The program is working properly now :)