I'm trying to make an application who sends querys to a tcp server who will then send an answer containing "rows" of commas separated values as an answer.
I'm pretty new to tcp programming, and it seems that i'm stuck here, because I can't read the answer when it comes. And since i don't know how many rows i will get (it can be arround 1000 sometimes) i can put my buffer too high neither...
here is the code I use...
Expand|Select|Wrap|Line Numbers
- private void WaitForData()
- {
- if (pfnCallBack == null)
- pfnCallBack = new AsyncCallback(OnDataReceived);
- // now start to listen for any data...
- m_asynResult = client.BeginReceive(m_DataBuffer, 0, m_DataBuffer.Length, SocketFlags.None, pfnCallBack, null);
- }
- public void OnDataReceived(IAsyncResult asyn)
- {
- //end receive...
- int iRx = 0;
- iRx = client.EndReceive(asyn);
- char[] chars = new char[iRx + 1];
- System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
- int charLen = d.GetChars(m_DataBuffer, 0, iRx, chars, 0);
- System.String szData = new System.String(chars);
- if (isNewData)
- {
- isNewData = false;
- receivedData = szData;
- }
- else
- {
- receivedData = receivedData + szData;
- }
- WaitForData();
- }
- // Fonction sendMessage
- // -- Sert a envoyé un message à l'hôte de la connection client
- // -- Reçoit en parametre un message de type string
- // -- Envoie un erreur à la console si il y a un problème
- // -- Sends message to the server
- public void sendMessage(String message)
- {
- try
- {
- message = message + "\r\n";
- byte[] byData = System.Text.Encoding.ASCII.GetBytes(message);
- isNewData = true;
- client.Send(byData);
- WaitForData();
- }
- catch (SocketException se)
- {
- MessageBox.Show(se.Message);
- }
- }
- public string getMessage()
- {
- string retour;
- if (receivedData != "")
- {
- retour = receivedData;
- }
- else
- {
- retour = "Chaîne vide!";
- }
- return retour;
- }
Expand|Select|Wrap|Line Numbers
- unClient.sendMessage(message);
- reponse = unClient.getMessage();
anyone got an idea how to resolve this problem? any mechanism that can wait till all the data is received before to put it in the reponse variable?
Thanx