Tcp / IP实例使端口忙 [英] Tcp/IP instance keeps port busy
问题描述
大家好,
我有一个应用程序,我试图通过以太网与硬件进行通信。我的应用程序有2个按钮,一个用于连接和另外发送命令。
连接按钮点击事件如下所示:
Hi All,
I have an application through which i am trying to communicate with the hardware via ethernet. My application has 2 buttons, one to connect & other to send commands.
Connect button click event is as shown below:
private void btnConnect_Click(object sender, EventArgs e)
{
client = new TcpClient();
client.SendTimeout = SEND_TIMEOUT;
client.ReceiveTimeout = RESPONSE_TIMEOUT;
client.Connect(DeviceIPAddress, DevicePortNumber);
if (!client.Connected)
{
throw new Exception("Device not connected");
}
}
private void btnSendCmd_Click(object sender, EventArgs e)
{
using (client = new TcpClient(DeviceIPAddress, DevicePortNumber))
{
client.SendTimeout = SEND_TIMEOUT;
client.ReceiveTimeout = RESPONSE_TIMEOUT;
string commandResponse = null;
byte[] sendDataBuffer;
byte[] receiveDataBuffer = new byte[1024];
// other process takes places here
}
}
问题是每当我点击在连接按钮上,创建了TCP实例&港口一直很忙。连接后,如果我尝试单击SendCommand按钮,则会抛出错误,说无法通信。
非常感谢任何形式的帮助。
提前致谢,
Jagadisha。 N $ / $
我尝试了什么:
我试过评论下面的内容连接按钮点击事件中的代码行,但问题仍然相同。
The problem is whenever i click on connect button, the TCP instance is created & the port is kept busy. And after connecting, if i try to click on SendCommand button it throws error saying unable to communicate.
Any kind of help is really appreciated.
Thanks in advance,
Jagadisha. N
What I have tried:
I tried commenting the below lines of code in connect button click event, but the issue remains the same.
//client.SendTimeout = SEND_TIMEOUT;
//client.ReceiveTimeout = RESPONSE_TIMEOUT;
推荐答案
您的连接按钮创建客户端并连接到设备。您的发送按钮然后创建一个新客户端,不使用该客户端连接,然后尝试发送数据。
您需要从连接中重新使用客户端您的发送代码中的代码,因此删除using(client =行,当代码引用client时,它将引用您在连接代码中创建的客户端。
Your connect button create a client and connects to the device. Your send button then creates a new client, doesn't connect using that client, then tries to send data.
You need to re-use the client from your connect code in your send code, so remove the "using (client =" line and when the code references "client" it'll reference the client you created in the connect code.
这篇关于Tcp / IP实例使端口忙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!