c#-4.0 – 使用带有TCPIP接口的C#中执行的ESCPOS命令直接打印到热敏打印机

c#-4.0 – 使用带有TCPIP接口的C#中执行的ESCPOS命令直接打印到热敏打印机,第1张

概述我正在厨房打印机(Aclas KP71M)上实施ESC / POS(Epson销售点标准代码). 我有一个用户界面,POS用户将其字符串输入到用户界面,用户输入的字符串将被发送到打印机,打印机打印数据. 打印机与主机的接口使用以太网(100M)使用TCP / IP连接.我已经设法将每个必要的命令嵌入到C#方法中,我还在服务器/客户端C#上采用了一些示例代码 连接并尝试将其包含在我的连接中.  我现 我正在厨房打印机(Aclas KP71M)上实施ESC / POS(Epson销售点标准代码).
我有一个用户界面,POS用户将其字符串输入到用户界面,用户输入的字符串将被发送到打印机,打印机打印数据.
打印机与主机的接口使用以太网(100M)使用TCP / IP连接.我已经设法将每个必要的命令嵌入到C#方法中,我还在服务器/客户端C#上采用了一些示例代码
连接并尝试将其包含在我的连接中.
我现在面临的问题是我的代码似乎开始连接但它立即冻结
没有做任何事情并且停止了连接.如果有人可以纠正我,或者告诉我问题所在,或者让我知道如何继续,我将非常感激?
这是代码.
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.linq;using System.Text;using System.windows.Forms;using System.Net;using System.Net.sockets;namespace ESC_POS{   public partial class Form1 : Form   {        public string tableNumber;        public string itemOrdered;        public string orderedQuantity;        public string waitername;        public string orderDestination;        public string orderNumber;        const int MAX_CLIENTS = 10;        public AsyncCallback pfnWorkerCallBack;        private Socket m_mainSocket;        private Socket[] m_workerSocket = new Socket[10];        private int m_clIEntCount = 0;//Server declarations        byte[] m_dataBuffer = new byte[10];        IAsyncResult m_result;        public AsyncCallback m_pfnCallBack;        public Socket m_clIEntSocket;//ClIEnt declarations        public Form1()        {            InitializeComponent();            PC_IP.Text = GetIP();            PRINTER_IP.Text = GetIP();        }        public voID label1_Click(object sender,EventArgs e)        {        }        public voID Form1_Load(object sender,EventArgs e)        {        }           public voID tableNumber_TextChanged(object sender,EventArgs e)        {            if (tableNumber.Text == "")            {                MessageBox.Show("Please enter the table number");                return;            }            tableNumber = tableNumber.Text;        }        public voID OrderedQuantitiy_TextChanged(object sender,EventArgs e)        {            if (OrderedQuantitiy.Text == "")            {                MessageBox.Show("Please enter the ordered quantity");                return;            }            orderedQuantity = OrderedQuantitiy.Text;        }        public voID Waitername_TextChanged(object sender,EventArgs e)        {            if (Waitername.Text == "")            {                MessageBox.Show("Please enter the waiter name");                return;            }            waitername = Waitername.Text;        }        public voID comboOrderDestination_SelectedindexChanged(object sender,EventArgs e)        {            if (ItemOrdered.Text == "")            {                MessageBox.Show("Please select the order destiination");                return;            }            orderDestination = comboOrderDestination.SelectedText;        }        public voID OrderNumber_TextChanged(object sender,EventArgs e)        {            if (OrderNumber.Text == "")            {                MessageBox.Show("Please enter the order number");                return;            }            orderNumber = OrderNumber.Text;        }        public voID Printbutton_Click(object sender,EventArgs e)        {            try            {                   string[] printData = new string[6];                printData[0]=tableNumber ;                printData[1]= itemOrdered;                printData[2]= orderedQuantity;                printData[3]= waitername;                printData[4]= orderDestination;                printData[5]= orderNumber;                string richTextMessage = "";                PrinterCommands printCmd = new PrinterCommands();                printCmd.initializePrinter();                PrinterCommands print = new PrinterCommands();                for (int i = 0; i < printData.Length; i++)                {                    richTextMessage = printData[i]+" ";                    richTextMessage = print.lineFeed().ToString();                }                Object objData = richTextMessage;                byte[] byData = System.Text.EnCoding.ASCII.GetBytes(objData.ToString());                if (m_clIEntSocket != null)                {                    m_clIEntSocket.Send(byData);                }            }            catch (SocketException se)            {                MessageBox.Show(se.Message);            }        }        public voID textBox1_TextChanged(object sender,EventArgs e)        {        }        public voID PC_PORT_TextChanged(object sender,EventArgs e)        {        }        public voID PRINTER_IP_TextChanged(object sender,EventArgs e)        {        }        public voID PRINTER_PORT_TextChanged(object sender,EventArgs e)        {        }        public voID Connect_topC_Click(object sender,EventArgs e)        {            // See if we have text on the IP and Port text fIElds            // See if we have text on the IP and Port text fIElds            if (PRINTER_IP.Text == "" || PRINTER_PORT.Text == "")            {                MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");                return;            }            try            {                UpdateControlsPrinter(false);                // Create the socket instance                m_clIEntSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);                // Cet the remote IP address                IPAddress ip = IPAddress.Parse(PRINTER_IP.Text);                int iPortNo = System.Convert.ToInt16(PRINTER_PORT.Text);                // Create the end point                 IPEndPoint ipEnd = new IPEndPoint(ip,iPortNo);                // Connect to the remote host                m_clIEntSocket.Connect(ipEnd);                if (m_clIEntSocket.Connected)                {                    UpdateControlsPrinter(true);                    //Wait for data asynchronously                     WaitForData();                }            }            catch (SocketException se)            {                string str;                str = "\nConnection Failed,is the server running?\n" + se.Message;                MessageBox.Show(str);                UpdateControlsPrinter(false);            }               }        public voID ItemOrdered_TextChanged_1(object sender,EventArgs e)        {            if (ItemOrdered.Text == "")            {                MessageBox.Show("Please enter the Item Ordered");                return;            }        }        public voID disconnect_topC_Click(object sender,EventArgs e)        {            if (m_clIEntSocket != null)            {                m_clIEntSocket.Close();                m_clIEntSocket = null;             UpdateControlsPrinter(false);            }            Close();        }        public voID Start_Listening_Click(object sender,EventArgs e)        {            try            {                // Check the port value                if (PC_PORT.Text == "")                {                    MessageBox.Show("Please enter a Port Number");                    return;                }                string portStr = PC_PORT.Text;                int port = System.Convert.ToInt32(portStr);                // Create the Listening socket...                m_mainSocket = new Socket(AddressFamily.InterNetwork,ProtocolType.Tcp);                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any,port);                // Bind to local IP Address...                m_mainSocket.Bind(ipLocal);                // Start Listening...                m_mainSocket.Listen(4);                // Create the call back for any clIEnt connections...                m_mainSocket.BeginAccept(new AsyncCallback(OnClIEntConnect),null);                UpdateControls(true);            }            catch (SocketException se)            {                MessageBox.Show(se.Message);            }        }        public voID Stop_Listening_Click(object sender,EventArgs e)        {            CloseSockets();            UpdateControls(false);            Close();        }        String GetIP()        {            String strHostname = Dns.GetHostname();            // Find host by name            IPHostEntry iphostentry = Dns.GetHostByname(strHostname);            // Grab the first IP addresses            String IPStr = "";            foreach (IPAddress ipaddress in iphostentry.AddressList)            {                IPStr = ipaddress.ToString();                return IPStr;            }            return IPStr;        }        public voID CloseSockets()        {            if (m_mainSocket != null)            {                m_mainSocket.Close();            }            for (int i = 0; i < m_clIEntCount; i++)            {                if (m_workerSocket[i] != null)                {                    m_workerSocket[i].Close();                    m_workerSocket[i] = null;                }            }        }        public voID WaitForData()        {            try            {                if (m_pfnCallBack == null)                {                    m_pfnCallBack = new AsyncCallback(OnDataReceived);                }                SocketPacket theSocPkt = new SocketPacket();              //          theSocPkt.thisSocket = m_clIEntSocket;                // Start Listening to the data asynchronously                m_result = m_clIEntSocket.BeginReceive(theSocPkt.dataBuffer,theSocPkt.dataBuffer.Length,SocketFlags.None,m_pfnCallBack,theSocPkt);            }            catch (SocketException se)            {                MessageBox.Show(se.Message);            }        }        public voID WaitForData(System.Net.sockets.socket soc)        {            try            {                if (pfnWorkerCallBack == null)                {                    // Specify the call back function which is to be                     // invoked when there is any write activity by the                     // connected clIEnt                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);                }                SocketPacket theSocPkt = new SocketPacket();                theSocPkt.m_currentSocket = soc;                // Start receiving any data written by the connected clIEnt                // asynchronously                soc.BeginReceive(theSocPkt.dataBuffer,pfnWorkerCallBack,theSocPkt);            }            catch (SocketException se)            {                MessageBox.Show(se.Message);            }        }        public class SocketPacket        {            public System.Net.sockets.socket m_currentSocket;            public byte[] dataBuffer = new byte[1];        }        public voID UpdateControlsPrinter(bool connected)        {            Connect_topC.Enabled = !connected;            disconnect_topC.Enabled = connected;            string connectStatus = connected ? "Connected" : "Not Connected";           // textBoxConnectStatus.Text = connectStatus;        }        public voID UpdateControls(bool Listening)        {            Start_Listening.Enabled = !Listening;            Stop_Listening.Enabled = Listening;        }        public voID OnDataReceived(IAsyncResult asyn)        {            try            {                SocketPacket socketData = (SocketPacket)asyn.AsyncState;                int iRx = 0;                // Complete the BeginReceive() asynchronous call by EndReceive() method                // which will return the number of characters written to the stream                 // by the clIEnt                iRx = socketData.m_currentSocket.EndReceive(asyn);                char[] chars = new char[iRx + 1];                System.Text.Decoder d = System.Text.EnCoding.UTF8.GetDecoder();                int charLen = d.GetChars(socketData.dataBuffer,iRx,chars,0);                System.String szData = new System.String(chars);              //  richTextBoxReceivedMsg.AppendText(szData);                // Continue the waiting for data on the Socket                WaitForData(socketData.m_currentSocket);            }            catch (ObjectdisposedException)            {                System.Diagnostics.DeBUGger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");            }            catch (SocketException se)            {                MessageBox.Show(se.Message);            }        }        public voID OnClIEntConnect(IAsyncResult asyn)        {            try            {                // Here we complete/end the BeginAccept() asynchronous call                // by calling EndAccept() - which returns the reference to                // a new Socket object                m_workerSocket[m_clIEntCount] = m_mainSocket.EndAccept(asyn);                // Let the worker Socket do the further processing for the                 // just connected clIEnt                WaitForData(m_workerSocket[m_clIEntCount]);                // Now increment the clIEnt count                ++m_clIEntCount;                // display this clIEnt connection as a status message on the GUI                    String str = String.Format("ClIEnt # {0} connected",m_clIEntCount);               // textBoxMsg.Text = str;                // Since the main Socket is Now free,it can go back and wait for                // other clIEnts who are attempting to connect                m_mainSocket.BeginAccept(new AsyncCallback(OnClIEntConnect),null);            }            catch (ObjectdisposedException)            {                System.Diagnostics.DeBUGger.Log(0,"\n OnClIEntConnection: Socket has been closed\n");            }            catch (SocketException se)            {                MessageBox.Show(se.Message);            }        }    }}
解决方法 回答这个问题以防其他任何人出现同样的问题.这对我有用:
Socket clIEntSock = new Socket(AddressFamily.InterNetwork,ProtocolType.Tcp);clIEntSock.NoDelay = true;IPAddress ip = IPAddress.Parse("192.168.0.18");IPEndPoint remoteEP = new IPEndPoint(ip,9100);clIEntSock.Connect(remoteEP);EnCoding enc = EnCoding.ASCII;// line Feed hexadecimal valuesbyte[] bEsc = new byte[4];bEsc[0] = 0x0A;bEsc[1] = 0x0A;bEsc[2] = 0x0A;bEsc[3] = 0x0A;// Send the bytes over clIEntSock.Send(bEsc);// Sends an ESC/POS command to the printer to cut the paperstring output = Convert.tochar(29) + "V" + Convert.tochar(65) + Convert.tochar(0);char[] array = output.tochararray();byte[] byData = enc.GetBytes(array);clIEntSock.Send(byData);clIEntSock.Close();
总结

以上是内存溢出为你收集整理的c#-4.0 – 使用带有TCP / IP接口的C#中执行的ESC / POS命令直接打印到热敏打印机全部内容,希望文章能够帮你解决c#-4.0 – 使用带有TCP / IP接口的C#中执行的ESC / POS命令直接打印到热敏打印机所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1237159.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存