C#套接字打印到网络打印机 - 不打印

时间:2013-01-15 23:42:10

标签: c# sockets

我正在尝试模拟将原始数据发送到条形码打印机。由于我没有,我只是将一些文字发送到我网络上的佳能喷墨打印机。问题是当代码执行没有任何反应时。我从之前的帖子中得到了这段代码(谢谢你)。你能看到我可能遗失或做错的事吗?感谢。

namespace ConsoleAppTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "^XA" +
            "^FO335,22,^CI0^A0,14,14^FR^FDConta^FS" +
            "^FO368,22,^CI0^A0,14,14^FR^FDins^FS" +
            "^PQ1" + "^XZ";
            PrintToZebra zPrintToIP = new PrintToZebra("192.168.1.101",80, text);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace PMIConsoleAppTest
{
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; }

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

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

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

}
}

0 个答案:

没有答案