TCPClient:无法建立连接,因为目标计算机主动拒绝它

时间:2017-05-26 14:21:00

标签: c# sockets tcpclient zebra-printers

尝试将网络流写入套接字但收到以下错误:

No connection could be made because the target machine actively refused it

应用程序有一个并发的打印作业列表,所以当我们有东西要打印时,检查tcp客户端是否已连接,如果没有连接,请获取流,写入流和刷新。

示例代码如下:

/// <summary> Print via TCP </summary>
private void PrintViaTcp(object a)
{
    Debug.WriteLine($"Printing via TCP...");
    var labelData = a as LabelData;            

    // Send data to the label printer
    SendToLabelPrinter(labelData.Commands, labelData.PrinterAddress, labelData.Port);

    Debug.WriteLine(" -> Printed labelId : {0}", labelData.LabelId);
}

/// <summary> Send the native command to the label printer </summary>        
public void SendToLabelPrinter(string commands, string address, int? port)
{                        
    //Connect to tcp client if a connection does not exist
    if (!TcpClient.Connected) TcpClient.Connect(address, port ?? 9100);

    //Get the network stream
    var stream = TcpClient.GetStream();

    // Send command strings to printer
    //stream.Write(Encoding.ASCII.GetBytes(commands), 0, commands.Length);
    stream.Write(Encoding.GetEncoding(850).GetBytes(commands), 0, commands.Length);

    //Flush the buffer on the network stream
    stream.Flush();           
}

这适用于小型打印作业&lt; 100次打印,但当我超过100时,错误会随机出现错过的打印件。

2 个答案:

答案 0 :(得分:0)

分析和查找随机发生的TCP或网络问题的根本原因的最佳方法是开始查看Wireshark,它可以更好地了解正在发送的内容以及如何拒绝连接

同样在您的代码中,TCPClient上没有超时设置,请在发送或接收更多数据量时尝试设置更高的**timeouts**设置..这可能是问题所在。再次使用wireshark,您将了解连接如何关闭以及启动它的每个细节......只需查看FIN标志

Wireshark download

答案 1 :(得分:0)

网络堆栈一次可以处理一个连接,并且在它开始拒绝连接之前可以排队8个左右的连接。如果您发送许多单独的连接请求,您需要考虑拒绝并退回,直到打印机可以处理请求。

另一种选择是创建一个将所有打印作业发送到的打印处理程序。

当第一个请求与打印机打开连接时。 当新请求进入队列时。 如果连接没有使用一分钟关闭连接。