【发布时间】:2016-04-12 19:56:22
【问题描述】:
在我的代码中,我正在尝试使用计时器连接到继电器板,该计时器在每次滴答时都会调用一个方法。问题是当我运行我的应用程序时,我在前 3-4 个滴答声中成功获得了连接。但是,在那之后它无法连接。我无法弄清楚我的代码有什么问题。任何帮助,将不胜感激。我正在使用 asp.net
调用的方法:
private void open_ethernet_connection()
{
byte connected = 0;
TcpClient client = new TcpClient();
try
{
IAsyncResult result = client.BeginConnect(textBox_IP.Text.Substring(0, textBox_IP.Text.IndexOf(",")), GlobalClass.port, null, null);
bool success = result.AsyncWaitHandle.WaitOne(1000, true);
if (!success)
{
connected = 0;
client.Close();
Response.Write("Failed to connect");
}
else connected = 1;
if (connected == 1)
{
ns = client.GetStream();
ns.ReadTimeout = 1000;
SerBuf[0] = (byte)commands.GET_VER; // get version command for ETH RLY16/02, returns software version
transmit(1);
receive(3);
module_version = SerBuf[2]; //print the software version on screen
device_found = true;
}
}
catch (SocketException)
{
if (selected_port == "Custom IP")
{
Response.Write("Unable to connect to module at " + GlobalClass.ipaddress);
}
else Response.Write("Unable to connect to module at " + selected_port);
return;
}
}
【问题讨论】:
-
我认为这不是问题,但如果可能的话,您应该在处理完
TcpClient后将其丢弃,请使用using。此外,如果您要等待它与 WaitOne 同步,使用 Async 方法似乎毫无意义。 -
定时器的时间间隔是多少?
-
@Peter 使用
client.Connect(host, port)给出相同的结果。 -
@jgauffin 定时器的间隔为 2000 毫秒。
-
@Peter 非常感谢,你拯救了我的一天!
client.Close()完成了这项工作。