I have the following code which creates a nice little instant messenger for my program. I am running into trouble when I try to send a message to a user that is not logged into their chat window. It waits about 20 seconds, then throws the error message. In the meantime, the entire program is hung up while it is waiting for the response to go through.
Here is the code I have:
Private Sub SendMessageButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendMessageButton.Click
Try
If UserNameComboBox.Text = "" Or IPComboBox.Text = "" Or MessageToSendTextBox.Text = "" Then
MsgBox("Enter a User Name, enter an IP Address , and enter a message.", MsgBoxStyle.Exclamation)
Else
If stringlocalIP = "" Then
MsgBox("Please enter an IP Address for user you are sending to" & vbCrLf & "(in the Settings tab).", MsgBoxStyle.Exclamation)
Else
client = New TcpClient(stringlocalIP, 44444)
Dim writer As New StreamWriter(client.GetStream())
writer.Write(UserNameComboBox.Text + " says: " + MessageToSendTextBox.Text)
writer.Flush()
lastMessage = MessageToSendTextBox.Text
MessageToSendTextBox.Text = ""
End If
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
If listener.Pending = True Then
message = ""
client = listener.AcceptTcpClient
Dim reader As New StreamReader(client.GetStream())
While reader.Peek > -1
message = message + Convert.ToChar(reader.Read()).ToString
End While
Me.Focus()
ReceiveMessagesTextBox.Text = (ReceiveMessagesTextBox.Text + message + vbCrLf)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I believe I need to incorporate the TcpClient.ReceiveTimeout and/or TcpClient.SendTimeout but I am not sure where to place those in my code. I have tried all sorts of things and I am getting a little stuck, so I do appreciate any comments or suggestions.
Thanks