Click here to Skip to main content
15,112,217 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 18: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
   
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
Addy Tas 9-Dec-11 14:56pm
   
Hi,

I downloaded the App(s) which was, surprisingly enough, written in C#. Am I looking at the right thing here? all the items above were about VB.NET? Don't get me wrong, my experience in C# exceeds VB by a fair margin but... just a bit odd i guess.

Anyway; what should I be looking at?
btw; sorry about the late responce, got quite a nasty day today.
Addy Tas 9-Dec-11 17:17pm
   
Hi, I have updated your solution a bit, where can i send the result to?
Send me a mail with the details and I'll zip it up for you.
It would be nice to compair your code and my changes and see if you know which way i'm pointing. Some small pieces of advice:
- get familiar with naming conventions, if everybody names his stuff the same you can easily read / understand the code.

- Install the VS extention manager tools:
1) spellchecker :)
2) Productivity power tools
3) Solution explorer tools
3) Code alignment (just easy to have :) )
adadero 15-Dec-11 1:44am
   
Can I have you E-Mail address? Yes, I'm using both VB.Net and C#. I'm actually prefer C# for it has simpler code.
Addy Tas 15-Dec-11 8:47am
   
Hi,

yes you may have my email address but... how to get it to you and not risk tons of spam... any suggestions?
If you can find me in any of the discussions you can send your email addess to me personally. That should work i guess.
adadero 16-Dec-11 13:00pm
   
Or if you have FB account I will send you private message. Type your FB URL not email address.
Addy Tas 16-Dec-11 13:05pm
   
Sorry, no facebook for me. You can find me on linked-in though

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

  Print Answers RSS
Top Experts
Last 24hrsThis month



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