Client/Server communication with StreamSockets - client waits infinitely
<p>According to <a href="https://msdn.microsoft.com/en-us/library/windows/apps/mt280234.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow">MSDN</a> I have following code to create Client/Server communication with TCP/IP StreamSockets.</p>

<p>Server:</p>

<pre><code>public async void Start(int port)
{
    try
    {
        //Create a StreamSocketListener to start listening for TCP connections.
        StreamSocketListener socketListener = new StreamSocketListener();

        //Hook up an event handler to call when connections are received.
        socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

        //Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
        await socketListener.BindServiceNameAsync(port.ToString());
    }
    catch (Exception ex)
    {
        Debug.WriteLine("SocketServer could not start. " + ex.ToString());
    }
}

private async void SocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
    try
    {
        string request;

        //Read line from the remote client.
        using (Stream inStream = args.Socket.InputStream.AsStreamForRead())
        {
            using (StreamReader reader = new StreamReader(inStream))
            {
                request = await reader.ReadLineAsync();
            }
        }

        // Process command and get response
        SocketResponse response = ProcessRequest(request);
        string responseString = JsonHelper.ToJson&lt;SocketResponse&gt;(response);

        //Send the line back to the remote client.
        using (Stream outStream = args.Socket.OutputStream.AsStreamForWrite())
        {
            using (StreamWriter writer = new StreamWriter(outStream))
            {
                await writer.WriteLineAsync(responseString);
                await writer.FlushAsync();
            }
        }
    }
    catch(Exception ex)
    {
        Debug.WriteLine("SocketListener failed." + ex.ToString());
    }
}
</code></pre>

<p>Client:</p>

<pre><code>private async Task Start(int responseTimeout)
{
    CancellationTokenSource cts = new CancellationTokenSource();

    try
    {
        cts.CancelAfter(responseTimeout);

        //Create the StreamSocket and establish a connection to the echo server.
        socket = new StreamSocket();

        //The server hostname that we will be establishing a connection to. We will be running the server and client locally,
        //so we will use localhost as the hostname.
        HostName serverHost = new HostName(hostName);

        //Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc.
        //For the echo server/client application we will use a random port 1337.
        string serverPort = port.ToString();
        await socket.ConnectAsync(serverHost, serverPort).AsTask(cts.Token);
    }
    catch
    {
        socket.Dispose();
    }
}

public async Task&lt;SocketResponse&gt; SendCommand(SocketCommand command, int responseTimeout = 2000)
{
    // Connect to socket first
    await Start(responseTimeout);

    //Write data to the echo server.
    using (Stream streamOut = socket.OutputStream.AsStreamForWrite())
    {
        using (StreamWriter writer = new StreamWriter(streamOut))
        {
            // Serialize command to json and send
            string request = JsonHelper.ToJson&lt;SocketCommand&gt;(command);
            await writer.WriteLineAsync(request);
            await writer.FlushAsync();
        }
    }

    //Read data from the echo server.
    using (Stream streamIn = socket.InputStream.AsStreamForRead())
    {
        using (StreamReader reader = new StreamReader(streamIn))
        {
            string responseString = await reader.ReadLineAsync();
            return JsonHelper.FromJson&lt;SocketResponse&gt;(responseString);
        }
    }
}
</code></pre>

<p>I am encountering two issues with my code:</p>

<ol>
<li>I have to establish connection from client side before every request. What is the reason? </li>
<li>When I am sending bigger response from server (string is 3kb) client waits for the response infinitely, however server responded quickly. Moreover, if server is closed, response is read by client. What's going wrong with this?</li>
</ol>