Question: I'm developing a simple chat application that has a server and a client. I wanna use only one socket object in run-time. Example(Java Client) :

```
class POClient
{
    Socket socket;
    BufferedWriter out;

    POClient()
    {
        socket = new Socket("192.168.1.3", 4445);
        OutputStreamWriter osw = new OutputStreamWriter( socket.getOutputStream());
        out = new BufferedWriter(osw);
    }

    void SendMessage()
    {
        out.write("Hello");
        out.flush();//edit
        // On this line, I need to use out.close() but if I close it, also 
        // socket will be closed. I don't wanna this. I wanna use only one instance.
    }
}

```

C# Server : 

```
TcpClient client = listener.AcceptTcpClient();  //if a connection exists, the server will accept it

            StreamWriter writer = new StreamWriter(client.GetStream());
            StreamReader reader = new System.IO.StreamReader(client.GetStream());
            try
            {
                string line = "";
                while (true)
                {

                    line = reader.ReadToEnd();

                }
            }

```

If I don't use out.close(), 'reader' is waiting until out.close()

Where am I failing?

Answer: 
I think closing the connection is required for `ReadToEnd`. You would have to use other method like `Read()`.
In that case you would have to create a simple protocol of your own with simplest of forms being:

> 
> |Data-Len in 4 bytes|----Data-----|
> 
> 
> 

Then you would know how much to read and then read it. You would not have to close the connection in that case. 

Also make sure to consider endien issues (if there are any) when converting length to byte array and back.
Try using `StreamReader.ReadLine()` instead of `StreamReader.ReadToEnd()`, and before `out.flush()` add `out.newLine()`. This should write each message in new line and read from stream by lines.