2

what is the best way to read from NetworkStream to some delimiter (for example "\n")

I have following code:

        NetworkStream clientStream = tcpClient.GetStream();
        var message = new byte[4096];

        while (true)
        {
            int bytesRead = 0;

            try
            {
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                // Exception
            }
            Response(message);
        }

Problem is, that from client sends something like "Some text\n continues on newline" but I would like to answer first on "Some text", then accept next line and send response.

Jan Kirchner
  • 25
  • 1
  • 7

1 Answers1

4

If you just want to read a line then use StreamReader on your NetworkStream and call its ReadLine method:

NetworkStream strm = client.GetStream();
StreamReader reader = new StreamReader(strm);
String line = reader.ReadLine();
Camille Goudeseune
  • 2,934
  • 2
  • 35
  • 56
Abdullah Saleem
  • 3,701
  • 1
  • 19
  • 30
  • 1
    But can I specify delimiter? – Jan Kirchner Mar 14 '15 at 13:10
  • @JanKirchner `StreamReader` only provides basic methods like `ReadLine` and `ReadToEnd` you have to implement your own methods for custom delimiters – Abdullah Saleem Mar 14 '15 at 13:17
  • @JanKirchner read the answer to this question http://stackoverflow.com/questions/8387536/streamreader-readline-not-working-over-tcp-when-using-r-as-line-terminator provides a custom implementation to the ReadLine method you can do the same for other delimiters – Abdullah Saleem Mar 14 '15 at 13:19