المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : How would you clear a tcp buffer or detect if there is data there ?



C# Programming
05-14-2013, 11:41 AM
Ok, here is my problem:- I have a tcp connection to an instrument; it is the slave and I am it's master (it speaks only when spoken to). Below is an example of how this conversation might look:-
//Clear RXstring.Array.Clear(this.RXstring, 0, this.RXstring.Length);//Build and send message.sendMessage(buildMessage(Operation.Query));//Couple of seconds delay is required before checking the data.System.Threading.Thread.Sleep(2000);try{ //Receive response from the Chamber Controller int len = this.tcp_com.Receive(this.RXstring); //Convert received ASCII bytes to string string temp = ASCIIEncoding.ASCII.GetString(this.RXstring, 0, len); if(temp.Contains("DYNAMIC") { this.dynamic = true; } else { this.dynamic = false; } }
Problem is this:- Sometimes, the data can be truncated or for some reason, maybe too big for the buffer and so a bit gets left behind. If I try and read without there being any data, it becomes stuck so I have made my buffer 1024 bytes long and added some time to try and make sure it's all arrived.
I would like to be able to clear the port somehow so that I know that there is only valid data when I get a responce and not something left over from last rx. Alternativey, I would like to be able to ask if there is data there without it crashing; I could then retrieve and discard myself.
I know that there are other ways I could have implemented the tcp bit but this seemed the simplest at the time.
As usual, all thoughts and advise gratefully received...