我已经阅读了有关 SignalR 的几篇文章,并考虑了一个有趣的测试项目,我可以创建一个 Web 应用程序来轮询我的 onkyo 接收器的状态并在浏览器中显示结果。对于初始测试,我通过在 Application_Start 中使用以下代码成功地将服务器上的当前时间发送回客户端:
ThreadPool.QueueUserWorkItem(_ =>
{
dynamic clients = Hub.GetClients<KudzuHub>();
while (true)
{
clients.addMessage(DateTime.Now.ToString());
Thread.Sleep(1000);
}
});
在客户端javascript中,我有以下代码:
// 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();
所以所有这些都很好。每一秒,我都会得到一个包含当前服务器日期和时间的新列表项。
现在,当我添加此代码以从 Onkyo 接收器读取数据时,它会中断:(仍在 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
}
});
我设置了一个断点并单步执行了代码。它到达这条线,然后返回。
clientSockStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);
它永远不会完成将消息发送到客户端的其余代码。我究竟做错了什么?
谢谢。