C#套接字打印有时候没有响应?

时间:2012-08-08 06:21:15

标签: c# sockets zpl

我在打印到条形码打印机时遇到一些问题。代码工作正常,但我不能立即打印另一个,但需要等待几秒钟。我的代码有什么问题吗?

提前感谢任何人。

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

    }

}

}

1 个答案:

答案 0 :(得分:0)

谢谢约阿希姆。我使用BeginWrite而不是Write修改了我的代码并解决了问题。

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

}