使用ThreadPool.打开TcpClient连接并读取ASP中的数据.. NET和SignalR
本文关键字:数据 NET SignalR ASP 读取 打开 ThreadPool TcpClient 连接 使用 | 更新日期: 2023-09-27 18:16:40
我读了几篇关于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);
它永远不会完成向客户端发送消息的其余代码。我做错了什么?
谢谢。
我会对您的循环进行一些结构更改,以允许接收方有时间响应,消除每50毫秒检索配置的开销,并清理打开的网络流:
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();
}
}
});