views:

2510

answers:

3

Simply I have been trying to implement what BufferedStreamReader does in Java. I have a socket stream open and just want to read it in a line oriented fashion -line by line.

I have following server-code

while (continueProcess)
        {
            try
            {
                StreamReader reader = new StreamReader(Socket.GetStream(), Encoding.UTF8);
                string command = reader.ReadLine();
                if (command == null)
                    break;

                OnClientExecute(command);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

And the following client-code:

TcpClient tcpClient = new TcpClient();
        try
        {
            tcpClient.Connect("localhost", serverPort);
            StreamWriter writer = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);
            writer.AutoFlush = true;
            writer.WriteLine("login>user,pass");
            writer.WriteLine("print>param1,param2,param3");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            tcpClient.Close();
        }

Server reads only the very first line(login>user,pass) and then ReadLine returns null!

What's the easiest way of achieving this line oriented reader as it is in Java's BufferedStreamReader? :s

Thanks in advance

+5  A: 

The while in your server code is setup to only read one line per connection. You'll need another while within the try to read all of the lines being sent. I think once that stream is setup on the client side, it is going to send all of the data. Then on the server side, your stream is effectively only reading one line from that particular stream.

L. Moser
After altering my server and client code as followsserver:using (StreamReader reader = new StreamReader(Socket.GetStream(), Encoding.UTF8)) { while (continueProcess) ....client:... Thread.Sleep(10000); writer.WriteLine("print>test,one,two");I inserted Thread.Sleep(10000) to my client code and server started throwing exception. The client socket will be open till client exits and since client will send data throughout its lifecycle seems like this code will throw error. Don't you think so?
Aleyna
Without seeing what the new code or new exception is, I'm not sure what the problem might be.
L. Moser
+1  A: 

A typical line-reader is something like:

using(StreamReader reader = new StreamReader(Socket.GetStream(), Encoding.UTF8)) {
    string line;
    while((line = reader.ReadLine()) != null) {
        // do something with line
    }
}

(note the using to ensure we Dispose() it even if we get an error, and the loop)

If you want, you could abstract this (separation of concerns) with an iterator block:

static IEnumerable<string> ReadLines(Stream source, Encoding encoding) {
    using(StreamReader reader = new StreamReader(source, encoding)) {
        string line;
        while((line = reader.ReadLine()) != null) {
            yield return line;
        }
    }
}

(note we've moved this into a function and removed the "do something", replacing it with "yield return", which creates an iterator (a lazily iterated, non-buffering state machine)

We would then consume this as simply as:

foreach(string line in ReadLines(Socket.GetStream(), Encoding.UTF8)) {
    // do something with line
}

Now our processing code doesn't need to worry about how to read lines - simply given a sequence of lines, do something with them.

Note that the using (Dispose()) applies to TcpClient too; you should make a habit of checking for IDisposable; for example (still including your error-logging):

using(TcpClient tcpClient = new TcpClient()) {
    try {
       tcpClient.Connect("localhost", serverPort);
       StreamWriter writer = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);
       writer.AutoFlush = true;
       writer.WriteLine("login>user,pass");
       writer.WriteLine("print>param1,param2,param3");
    } catch (Exception ex) {
        Console.Error.WriteLine(ex.ToString());
    }
}
Marc Gravell