C#利用pos命令操作网口打印机的方法

    技术2022-06-26  50

    使用POS命令操作网口打印机的好处在于免驱动并且打印速度较快.

    方法一使用TcpClient类

    关键代码

      Int32 port = 9100;  string bigFont =((char)27).ToString() + ((char)33).ToString() + ((char)213).ToString();//放大字体                   TcpClient client = new TcpClient();            try            {                client.Connect("172.30.168.100", port);

                    Byte[] data = System.Text.Encoding.Default.GetBytes(bigFont);                NetworkStream stream = client.GetStream();                stream.Write(data, 0, data.Length);

                    data = System.Text.Encoding.Default.GetBytes(bigFont);                stream.Write(data, 0, data.Length);                data = System.Text.Encoding.Default.GetBytes("打印机测试/n");                stream.Write(data, 0, data.Length);                data = System.Text.Encoding.Default.GetBytes("-             -/n");                stream.Write(data, 0, data.Length);                data = System.Text.Encoding.Default.GetBytes("-             -/n");                stream.Write(data, 0, data.Length);                stream.Close();                            }            catch (Exception ex)            {

                    //如果打印机没开或者异常,在此处增加处理代码,我通常是把异常数据放到一个DataTable中,加个Timer来判断打印机正常就把

                    //数据发给打印机并从表中移除.

                    //打印机缺纸或者纸匣打开时,不会出现异常,不用特殊代码判断,数据不会丢失.            }            finally            {                client.Close();            }

    //-------------------------------------------------------------------------------------------------------------------------------------------

    方法二使用Socket类

        Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            try            {                sendSocket.Connect("172.30.168.100", 9100);

                    byte[] buffer = Encoding.Default.GetBytes(bigFont);

                    sendSocket.Send(buffer);                buffer = Encoding.Default.GetBytes("测试打印机/n");                sendSocket.Send(buffer);                sendSocket.Shutdown(SocketShutdown.Both);                          }            catch (Exception ex)            {                throw ex;            }            finally            {                sendSocket.Close();            }

    这两种方法均可实现免驱网口打印.


    最新回复(0)