2012-08-08 2 views
2

바코드 프린터에 인쇄하는 데 문제가 있습니다. 코드는 정상적으로 작동하지만 다른 카드를 즉시 인쇄 할 수는 없지만 몇 초 정도 기다려야합니다. 내 암호에 문제가 있습니까?C# 소켓 때때로 응답이 없습니까?

미리 감사드립니다.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 


namespace PrintToZebra 
{ 
class Program 
{ 
    public static void Main(string[] args) 
    { 
     Console.WriteLine("start printing to: 10.160.2.254:9100"); 
     string text = "^XA" + 
      "^FO335,22,^CI0^A0,14,14^FR^FDConta^FS" + 
      "^FO368,22,^CI0^A0,14,14^FR^FDins^FS" + 
      "^PQ1" + 
      "^XZ"; 
     printToIP("10.160.2.254", 9100, text); 


    } 


    public static void printToIP(string ipAddress, int printerPort, string content) 
    { 
     try 
     { 
      EndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddress), printerPort); 
      //EndPoint ep = new IPEndPoint(parseIP(ipAddress),printerPort); 
      Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
      sock.Connect(ep); 
      NetworkStream ns = new NetworkStream(sock); 
      byte[] toSend = Encoding.ASCII.GetBytes(content); 
      ns.Write(toSend, 0, toSend.Length); 
      sock.Close(); 
     } 
     catch(Exception ex) 
     { 
      Console.WriteLine(ex); 
     } 

    } 

} 

}

+3

각 인쇄 된 레이블 간의 연결을 닫아야합니까? 일부 프린터 (내 머리 꼭대기에서 얼룩말에 대해 잘 모름)는 각 연결 사이에 재설정 절차를 수행하여 다시 연결하는 데 지연이 발생할 수 있습니다. –

답변

0

감사 요아힘. Write 대신 BeginWrite를 사용하여 코드를 수정하고 문제를 해결합니다.

public class PrintToZebra 
    { 
     public string printerIP { get; set; } 
     public int printerPort { get; set; } 
     public string myZPL { get; set; } 
     private EndPoint ep { get; set; } 
     private Socket sock { get; set; } 
     private NetworkStream ns { get; set; } 
     //private AsyncCallback callbackWrite; 

    public PrintToZebra() 
    { 
     printerIP = ""; 
     printerPort = 0; 
     myZPL = ""; 
    } 


    public PrintToZebra(string anIP, int aPort, string aZPL) 
    { 
     printerIP = anIP; 
     printerPort = aPort; 
     myZPL = aZPL; 
    } 


    public void printToIP() 
    { 
     ep = new IPEndPoint(IPAddress.Parse(printerIP), printerPort); 
     sock = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 

     try 
     { 
      sock.Connect(ep); 
      ns = new NetworkStream(sock); 
      byte[] toSend = Encoding.ASCII.GetBytes(myZPL); 
      ns.BeginWrite(toSend, 0, toSend.Length, OnWriteComplete, null); 
      ns.Flush(); 
     } 
     catch (Exception ex) 
     { 
      //Console.WriteLine(ex.ToString()); 
      sock.Shutdown(SocketShutdown.Both); 
      sock.Close(); 
     } 

    } 

    private void OnWriteComplete(IAsyncResult ar) 
    { 
     NetworkStream thisNS = ns; 
     thisNS.EndWrite(ar); 
     sock.Shutdown(SocketShutdown.Both); 
     sock.Close(); 
    } 

}