Question

I've read a couple of posts on SignalR and thought for a fun test project that I could create a web application to poll my onkyo receiver for status and display the results in a browser. For an initial test, I was successfully able to send the current time on the server back to the client by using this code in Application_Start:

ThreadPool.QueueUserWorkItem(_ =>
{               
    dynamic clients = Hub.GetClients<KudzuHub>();
    while (true)
    {                
        clients.addMessage(DateTime.Now.ToString());

        Thread.Sleep(1000);
    }
});   

In the client javascript, i have the following code:

// Proxy created on the fly
var kHub = $.connection.kudzuHub;

// Declare a function on the hub so that the server can invoke it
kHub.addMessage = function (message) {
    console.log('message added');
    $('#messages').append('<li>' + message + '</li>');
};

// start the connection
$.connection.hub.start();

So all of that works fine. Every second, I get a new list item containing the current server date and time.

Now when I add this code to read data from the Onkyo receiver, it breaks: (still in Application_Start)

ThreadPool.QueueUserWorkItem(_ =>
{  
    dynamic clients = Hub.GetClients<KudzuHub>();
    try
    {
        while (true)
        {
            string host = ConfigurationManager.AppSettings["receiverIP"].ToString();
            int port = Convert.ToInt32(ConfigurationManager.AppSettings["receiverPort"]);

            TcpClient tcpClient = new TcpClient(host, port);

            NetworkStream clientSockStream = tcpClient.GetStream();

            byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
            clientSockStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);

            tcpClient.Close();

            clients.addMessage(System.Text.Encoding.ASCII.GetString(bytes));
            Thread.Sleep(50);
        }
    }
    catch (SocketException ex)
    {
        // do something to handle the error
    }

});

I set a break point and stepped through the code. It gets to this line and then returns.

clientSockStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);

It never finishes the rest of the code to send the message to the client. What am I doing wrong?

Thanks.

Was it helpful?

Solution

I would make some structural changes to your loop to allow the receiver time to respond, remove the overhead of retrieving the configuration every 50 milliseconds, and cleanup the open network stream:

ThreadPool.QueueUserWorkItem(_ =>
{  
    dynamic clients = Hub.GetClients<KudzuHub>();
    TcpClient tcpClient = null;
    NetworkStream clientSockStream = null;

    try
    {
        string host = ConfigurationManager.AppSettings["receiverIP"].ToString();
        int port = Convert.ToInt32(ConfigurationManager.AppSettings["receiverPort"]);

        while (true)
        {
            if (tcpClient == null) {
              tcpClient = new TcpClient(host, port);
              clientSockStream = tcpClient.GetStream();
            }

            if (clientSockStream.CanRead) {
                byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
                try {
                   clientSockStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);
                } catch (Exception ex) {
                  // Add some debug code here to examine the exception that is thrown
                }

                tcpClient.Close();
                // Closing the client does not automatically close the stream
                clientSockStream.Close();

                tcpClient = null;
                clientSockStream = null;

                clients.addMessage(System.Text.Encoding.ASCII.GetString(bytes));
            }
            Thread.Sleep(50);
        }
    }
    catch (SocketException ex)
    {
        // do something to handle the error
    } finally {
       if (tcpClient != null) {
         tcpClient.Close();
         clientSockStream.Close();
       }
    } 

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top