2017-05-26 43 views
-1

試圖寫網絡流套接字,但得到以下錯誤:的TcpClient:無連接可以作出,因爲目標機器積極地拒絕它

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();   
} 

這適用於小型打印作業< 100次印刷,但是當我去了100,誤差是隨機發生的失蹤打印。

+0

這似乎是一個併發問題。您應該檢查打印機服務器可以處理多少個併發作業 – yorodm

回答

0
分析和隨機發生是開始尋找Wireshark的,可以提供更多的有識之士正在發送和連接是如何

之間

也可以作爲拒絕找到的TCP或網絡問題根源

的最佳方式在您的代碼中沒有超時設置TCPClient請嘗試設置更高的**timeouts**設置時發送或接收更多的數據量..這可能是問題。再次使用Wireshark你就會知道每一個細節的連接是怎麼封閉,是誰發起它..只要看看FIN標誌

Wireshark download

0

網絡堆棧可以一次處理一個連接,並可以排隊8間左右的連接在它開始拒絕連接之前。如果您發送了很多單獨的連接請求,則需要考慮拒絕並退回,直到打印機可以處理請求。

另一種選擇是創建一個打印處理程序,您可以將所有打印作業發送到該處理程序。

當第一個請求進入到打印機的開放連接。 隨着新的請求進來,將它們添加到隊列中。 如果在一分鐘內沒有使用連接關閉連接。

相關問題