async await - How do you use C# NetworkStream ReadAsync() to only grab stuff between stx and etx? -
i'm trying build new application communicates finished application on tcp/ip. 2 applications pass messages , forth between each other. here of server code new application reads stuff in finished application:
public class asyncservice { private ipaddress ipaddress; private int port; char[] stx = new char[] { '' }; char[] etx = new char[] { '' }; networkstream networkstream; tcpclient tcpclient; private byte[] rawbuffer; private static readonly int rawbuffersize = 2024; public asyncservice(int port) { this.port = port; string hostname = dns.gethostname(); iphostentry iphostinfo = dns.gethostentry(hostname); rawbuffer = new byte[rawbuffersize]; this.ipaddress = ipaddress.any; if (this.ipaddress == null) { throw new exception("no ipv4 address server"); } } public async void run() { tcplistener listener = new tcplistener(this.ipaddress, this.port); listener.start(); while (true) { try { tcpclient = await listener.accepttcpclientasync(); networkstream = tcpclient.getstream(); doreadasync(rawbuffer); } catch (exception ex) { debug.writeline(ex.message); } } } private void doreadasync(byte[] bytebuffer) { task<int> t = networkstream.readasync(bytebuffer, 0, bytebuffer.length); t.continuewith((task, bytes) => onreadcompleted((byte[])bytes, task.result), bytebuffer, taskcontinuationoptions.onlyonrantocompletion); } private void onreadcompleted(byte[] bytebuffer, int length) { if (length == 0) { return; } string message = asciiencoding.ascii.getstring(bytebuffer); //... array.clear(bytebuffer, 0, bytebuffer.length); doreadasync(bytebuffer); } every message sent preceded stx character , ended etx character. problem there times when new application receives more 1 message @ time. example, might receive message this:
[stx]123456789[etx][stx]10111213141516171819[etx]
i want make code read until hit etx character. thus, want above example 2 messages don't know how readasync(). know how can this?
you have 2 choices. read whole stream string , parse it, or parse stream on fly reading byte byte , stopping when reach "magic" combo of bytes. personally, if datastream not massive option 1 easier achieve hth
Comments
Post a Comment