-1
您好,我目前正在每分钟创建一个与斑马打印机的新连接,并且它可以正常工作5到8个小时。之后,我得到了“无法建立连接,因为目标机器主动拒绝了”错误。一旦出现此错误,在完全关闭并打开Zebra打印机的电源之前,无法重新连接打印机。C# - TcpClient - 由于目标机器主动拒绝而无法建立连接
我我没有正确关闭我的TcpClient的蒸汽或什么都不会造成约300后出现错误重新连接
我的代码:
//CLASS MEMBERS
private TcpClient client = new TcpClient();
private Timer TimZebraTimeOut;
private int ZebraTimeOutTime = 60000;
private bool NewConnectionNeeded = true;
//NORMALY CALLED IN CONSTRUCTOR
TimZebraTimeOut = new Timer(TimZebraTimeOutCallback, null,this.ZebraTimeOutTime, Timeout.Infinite);
//CLASS METHODS
private void CreateNewConnectionIfComTimeOut
{
try
{
if (this.NewConnectionNeeded) // If time is out Create new connection with Zebra Printer
{
//Close last connexion open
client.Client.Close();
//Create a new one
client = new TcpClient();
// Add Read/Write TimeOut
client.SendTimeout = 10000;
client.ReceiveTimeout = 10000;
//Create TCP Connection
client.Connect(this.config.IpAddress, this.config.Port);
// Connection with PrinterEstablished
this.NewConnectionNeeded = false;
this.iLog.Info("CommunicationWithZebraPrinter : New connection With Labeler Established "); // If New connection not caused by timeout
}
}
catch (Exception exception)
{
// Write exception in Log
this.iLog.Error("CommunicationWithZebraPrinter : Can't establish a connection with printer: " + exception.Message.ToString());
}
}
// Zebra Communication Timer interrupt callback function
private void TimZebraTimeOutCallback(Object state)
{
// Flag That ZebraCom have timeout
this.NewConnectionNeeded= true;
//Restart Zebra Com TimeOut
TimZebraTimeOut.Change(this.ZebraTimeOutTime, Timeout.Infinite);
}
非常感谢
丹尼尔
Netstat查看:
当新的连接建立时,3个本地端口增加。
使用sysinternals的tcpview查看有多少个连接窗口认为从您到打印机 – pm100
在TimeWait和1 In Established中始终存在2个连接,并且创建新连接时,所有端口号都会递增。我会在我的问题中添加一张图片。 –
我会做client.dispose不client.Client.Close。另外我会在需要时打开连接(使用),然后关闭它。不要保持连接比你需要的更长 – pm100