简体   繁体   中英

C# Asynchronous read over tcp/ip

I need to create a client that connects to a medical machine over tcpip. This machine, upon internal event, send me one or more XML file with the data I need to process. As these events are not pretictable, I thought about asynchronous connection which get the data and save it on filesystem. Basically for each XML send by that machine I have to save it onto disk.

I googled a bit as I have not much experience in tcp/ip programming and I found on MSDN an example of asynchronous client ( Client Example )

First of all, doesn't work property as Console.WriteLine("Response received : {0}", response); is never hit. Then when that machine send me just one file, on the buffer I have same data twice. And also I'm guessing how to detect EOF among xml files sent.

I also thought about polling but seems to be uncorrect as solution. Any hints?

I pretty sure polling will not help in this case.

Few things that can show you some good pointers to start with:

1). Socket gives you the received data in some pre-defined provided byte array of the size you decide so decide the size well. Eg:

public const int BufferSize = 256;

for the example at MSDN, is 256, now if your data is of 260 bytes in size it will first send you the 256 bytes and then on the next receive it will send you the rest 4 bytes. This can be the one reason you need to find a way to pile up all this data received and then each time check for an start identifier and end identifier to extract the data that you need. From another view if you define a bigger byte buffer size considering the average size of your data. In most of the case you will receive the entire message in one go. But still you cannot achieve it 100% and that is the way socket works.

2). You might have received the data twice or some kind of broken data because the buffer byte array is not cleared at the proper time or is not flushed before next use.

3). EOF or EOT can be decided in may ways, if you have control on the medical machine you can insert an identifier at the end before it sends the data and use the same to differentiate the messages sent. If you dont have programmatic control on the sender and you are sure of XML format to be received you can always try to find the "<xml>" "</xml>" text in the data received and differentiate on that basis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM