Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi, I am trying to create a simple Client Server application. I have problem with AsyncCallBack. This code generates no errors but when a message sent, it doesn't show the message in txtMessage.Text (TextBox). Please help me how to write AsyncCallBack in the right way. Here is my code.
Dim NetStream As NetworkStream 'NetworkStream to send text in stream
Dim AsynCallback As AsyncCallback
Dim Client As TcpClient = New TcpClient() 'TcpClient to connect to the server
Dim ByteStream() As Byte 'Data in bytes

Private Sub Login()
    Try
        If IsNothing(Client) Then
            Client = New TcpClient()
        End If

        With Client
            '.NoDelay = True
            .Connect("server", 5482)

        End With

        If Client.Connected = True Then
            Dim mData As String = "This is Client"

            Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes(mData)
            NetStream = Client.GetStream()
            NetStream.Write(data, 0, data.Length)

            If Client.Connected = True Then
                Dim nAsynCallback As AsyncCallback = New AsyncCallback(AddressOf DataReceived)
            End If

        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

Private Sub DataReceived(ByVal AsyncResults As IAsyncResult)
    Try
        ReDim ByteStream(Client.ReceiveBufferSize) 'Data in bytes
        If NetStream.CanRead Then
            NetStream.BeginRead(ByteStream, 0, Convert.ToInt16(NetStream.Length), New AsyncCallback(AddressOf CallBack), NetStream)
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

End Sub

Private Sub CallBack(ByVal AsyncResults As IAsyncResult)
    'NetStream = CType(AsyncResults.AsyncState, NetworkStream)
    'Dim i As Integer = NetStream.EndRead(AsyncResults)
    NetStream.EndRead(AsyncResults)
    Me.txtMessages.Text = System.Text.Encoding.ASCII.GetString(ByteStream)
    AsynCallback = New AsyncCallback(AddressOf DataReceived)
End Sub
Posted
Updated 8-Dec-11 17:36pm
v2

1 solution

You need to handle the result of the read in the Callback and send it to the UI from there.
The way it is currently setup looks like a synchronous read which just doest't work async.

And with a bit more explanation:

VB
Dim NetStream As NetworkStream 'NetworkStream to send text in stream
Dim AsynCallback As AsyncCallback
Dim Client As TcpClient = New TcpClient() 'TcpClient to connect to the server
Dim ByteStream(1024) As Byte
Private Sub Login()
	Try
		If IsNothing(Client) Then
			Client = New TcpClient()
		End If
		With Client
			'.NoDelay = True
			.Connect("127.0.0.1", 5482)
		End With
		If Client.Connected = True Then
			Dim mData As String = "This is Client"
			Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes(mData)
			NetStream = Client.GetStream()
			NetStream.Write(data, 0, data.Length)
			If Client.Connected = True Then
		NetStream.BeginRead(ByteStream, 0, ByteStream.Length, New AsyncCallback(AddressOf CallBack), NetStream)
			End If
		End If
	Catch ex As Exception
		MessageBox.Show(ex.Message)
	End Try
End Sub
Private Sub CallBack(ByVal AsyncResults As IAsyncResult)
	NetStream.EndRead(AsyncResults)
	Console.WriteLine(System.Text.Encoding.ASCII.GetString(ByteStream))
	'Me.txtMessages.Text = System.Text.Encoding.ASCII.GetString(ByteStream) 'this needs to be invoked :) 
	NetStream.BeginRead(ByteStream, 0, ByteStream.Length, New AsyncCallback(AddressOf CallBack), NetStream)
End Sub


Now I know that I kindly step over little things as makeing sure that the buffer is not accessed outside by another thread etc. You might also take a good look at Invoking the Me.txtMessages.Text to get it on the UI thread. not that this agian depends on how you start the async call.

in any case it's always better to do the
if(InvokeRequired)
  Invoke(...


I'm pretty sure this is all you need to get going again.

Cheers, AT
 
Share this answer
 
v3
Comments
adadero 8-Dec-11 15:53pm    
I don't understand how to. Could you give me more explanation or sample code, please?
Addy Tas 8-Dec-11 16:43pm    
Hi,

Added the example to the answer, I guess that'll cover it.

Cheers, AT
adadero 8-Dec-11 23:39pm    
Hi, I have improve my question. That's my complete code. I have tried your suggestion and it still can't display the data received. I'm very upset and confused. Help me, please.
Addy Tas 9-Dec-11 3:44am    
Hi,

I tested the changes I just made and this was working for me. as you might notice i put the data to the console instead of the txt box. You will need to do the invoking on that one yourself.

This should really make you happy. If this works for you; please upvote & accept the answer.

Cheers, AT
adadero 9-Dec-11 5:42am    
Is it true to add such below code to invoke in textbox?
Private Sub CallBack(ByVal AsyncResults As IAsyncResult)
..........
..........
invoker = New MethodInvoker(AddressOf ToTextBox)
invoker.Invoke()
End Sub

Private Sub ToTextBox()
Me.txtMessages.Text = System.Text.Encoding.ASCII.GetString(ByteStream)
End Sub
Thank you so much for helping me. I appreciate that. This code is actually receiving data from Yahoo Messenger and it works. I have another question, I hope you can help me again. I can't create a client server chat application, here's what I've done so far. http://www.mediafire.com/?scxx268bty4uy49

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900