我正致力于在厨房打印机 (Aclas KP71M) 上实现 ESC/POS(爱普生销售点标准代码)。
我有一个用户界面,POS 用户将其字符串输入到用户界面,用户输入的字符串将被发送到打印机,打印机打印数据。
打印机与主机的接口(interface)使用以太网(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,
SocketType.Stream,
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,
0, 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, 0,
theSocPkt.dataBuffer.Length,
SocketFlags.None,
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,
0, 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, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
}
}
最佳答案
回答这个问题以防其他人遇到同样的问题。这对我有用:
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 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 values
byte[] 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 paper
string 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 - 使用在 C# 中执行的带有 TCP/IP 接口(interface)的 ESC/POS 命令直接打印到热敏打印机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11578355/
我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha
C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.
1.postman介绍Postman一款非常流行的API调试工具。其实,开发人员用的更多。因为测试人员做接口测试会有更多选择,例如Jmeter、soapUI等。不过,对于开发过程中去调试接口,Postman确实足够的简单方便,而且功能强大。2.下载安装官网地址:https://www.postman.com/下载完成后双击安装吧,安装过程极其简单,无需任何操作3.使用教程这里以百度为例,工具使用简单,填写URL地址即可发送请求,在下方查看响应结果和响应状态码常用方法都有支持请求方法:getpostputdeleteGet、Post、Put与Delete的作用get:请求方法一般是用于数据查询,
classPacketdefinitialize(name,age,number,array)@name=name@age=age@number=number@neighbors=arrayendendp1=Packet.new("n1",5,2,[1,2,3,4])putsp1.name我有上面的代码,但是每当我执行puts语句时,我都会收到nameisnotamethod的错误。我不知道任何其他方式来打印p1的名称。如何打印姓名? 最佳答案 这里的问题是,虽然您拥有实例变量,但您并未使它们可访问。attr_reader:vari
我正在使用mechanize登录网站,然后检索页面。我遇到了一些问题,我怀疑这是由于cookie中的某些值造成的。当Mechanize登录网站时,我假设它存储了cookie。如何通过Mechanize打印出存储在cookie中的所有数据? 最佳答案 代理有一个cookie方法。agent=Mechanize.newpage=agent.get("http://www.google.com/")agent.cookiesagent.cookies.to_scookie返回一个Mechanize::Cookiesobject
有没有办法快速将表格格式的ruby哈希打印到文件中?如:keyAkeyBkeyC...1232343451253474456...其中散列的值是不同大小的数组。还是使用双循环是唯一的方法?谢谢 最佳答案 试试我写的这个gem(在表中打印散列、ruby对象、ActiveRecord对象):http://github.com/arches/table_print 关于ruby-如何以表格格式快速打印Ruby哈希值?,我们在StackOverflow上找到一个类似的问题:
我们有一个目前在Rails2.3.12版和Ruby1.8.7版上运行的应用程序。我们想将我们的应用程序更新到Rails4.0和Ruby2.1.0。我们有大约200个模型和150个Controller。我想知道升级过程需要多大的努力。您还可以提供升级可以遵循的步骤。我们应该先升级Ruby然后再升级Rails还是相反? 最佳答案 您想要实现的目标将是史诗般的努力。我无法为您提供分步说明,因为不可能在一个答案中涵盖所有情况。我建议不要同时升级Ruby和Rails,而是分步升级。升级本身的复杂性是巨大的,但只要您的应用程序具有合理的测试覆盖
我如何做Ruby方法"Flatten"RubyMethod在C#中。此方法将锯齿状数组展平为一维数组。例如:s=[1,2,3]#=>[1,2,3]t=[4,5,6,[7,8]]#=>[4,5,6,[7,8]]a=[s,t,9,10]#=>[[1,2,3],[4,5,6,[7,8]],9,10]a.flatten#=>[1,2,3,4,5,6,7,8,9,10 最佳答案 递归解决方案:IEnumerableFlatten(IEnumerablearray){foreach(variteminarray){if(itemisIEnume