如何使用客户端程序通过以太网从天平读取数据



我必须通过以太网将Avery ZM510秤连接到电脑。基本上,当用户按下打印按钮时,它应该监听数据的刻度。供应商表示,该规模已经配置为服务器,并提供了IP,并表示不需要端口号。

我试过下面的客户端程序,但没有成功。埃弗里手册也没有包含任何关于API的信息。

using System;  
using System.Net;  
using System.Net.Sockets;  
using System.Text;  

public class SocketClient  
{  
public static int Main(String[] args)  
{  
StartClient();  
return 0;  
}  


public static void StartClient()  
{  
byte[] bytes = new byte[1024];  

try  
{  

IPHostEntry host = Dns.GetHostEntry("localhost");  
IPAddress ipAddress = host.AddressList[0];  
IPEndPoint remoteEP = new IPEndPoint(ipAddress, "");  


Socket sender = new Socket(ipAddress.AddressFamily,  
SocketType.Stream, ProtocolType.Tcp);  

// Connect the socket to the remote endpoint. Catch any errors.    
try  
{  
// Connect to Remote EndPoint  
sender.Connect(remoteEP);  

Console.WriteLine("Socket connected to {0}",  
sender.RemoteEndPoint.ToString());  

// Encode the data string into a byte array.    
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");  

// Send the data through the socket.    
int bytesSent = sender.Send(msg);  


int bytesRec = sender.Receive(bytes);  
Console.WriteLine("Echoed test = {0}",  
Encoding.ASCII.GetString(bytes, 0, bytesRec));  

// Release the socket.    
sender.Shutdown(SocketShutdown.Both);  
sender.Close();  

}  
catch (ArgumentNullException ane)  
{  
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());  
}  
catch (SocketException se)  
{  
Console.WriteLine("SocketException : {0}", se.ToString());  
}  
catch (Exception e)  
{  
Console.WriteLine("Unexpected exception : {0}", e.ToString());  
}  

}  
catch (Exception e)  
{  
Console.WriteLine(e.ToString());  
}  
}  
}  

配置Scale IP和端口,任何简单的客户端程序都可以工作。

public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
clientSocket.Connect("192.168.1.1", 8888); // Scale Ip and port
label1.Text = "Client Socket Program - Server Connected ...";
}
private void button1_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();

byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
msg(returndata);
textBox2.Text = "";
textBox1.Focus();
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}

通常,在销售AWTX ZM510时,它会配置一个静态IP,以向192.168.1.51端口1发送打印字符串。(除非设置它的技术人员更改了这些值。(

通过打开终端客户端(如PuttY(中的端口来测试此套接字。(telnet 192.168.1.51:1(然后按PRINT按钮。

之后,您可以用C#编写套接字应用程序

--我的工作是为Avery设备提供技术支持——ZM510是一款功能强大的设备。

最新更新