Here is a code sample of a simple TCP client that reads data from the IP voltmeter. It sends the command "volt_1" to the TCP server and the TCP server sends the measured value on the first channel. This way it is possible to read data on all channels.
The transfer involves only a few bytes, making it a highly efficient and speedy communication method.
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class Program
{
static void Main(string[] args)
{
string server = "192.168.0.60";
int port = 9760;
try
{
TcpClient client = new TcpClient();
client.Connect(server, port);
Console.WriteLine("Connected to the server.");
NetworkStream stream = client.GetStream();
while (true)
{
try
{
string message = "volt_1";
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
byte[] buffer = new byte[256];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Voltage: " + response + "V");
Thread.Sleep(1000);
}
catch (Exception e)
{
Console.WriteLine("Error during communication: " + e.Message);
break;
}
}
stream.Close();
client.Close();
Console.WriteLine("Connection closed.");
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
This C# program establishes a connection to a server at IP address 192.168.0.60
on port 9760
. Here's a detailed commentary on its functionality:
System
: Provides basic system functionality.System.Net.Sockets
: Provides the classes for network access.System.Text
: Provides classes for encoding strings.System.Threading
: Provides classes for multithreading.The TcpClient
class is used to connect to the server. If the connection is successful, it prints "Connected to the server." The NetworkStream
associated with the client is obtained for reading and writing data.
The program enters an infinite loop where it sends a message ("volt_1") to the server every second. This loop continues until an error occurs or the connection is manually interrupted.
Encoding.ASCII.GetBytes(message)
: Converts the message string to a byte array.stream.Write(data, 0, data.Length)
: Sends the byte array to the server.stream.Read(buffer, 0, buffer.Length)
: Reads the response from the server into a buffer.Encoding.ASCII.GetString(buffer, 0, bytesRead)
: Converts the received byte array back to a string.Thread.Sleep(1000)
: Pauses the loop for 1 second before repeating.Both the connection attempt and the communication loop have try-catch
blocks to handle potential exceptions. If an error occurs, it prints an error message and exits the loop.
When the loop ends (due to an error or manual interruption), the network stream and the client are closed, and a "Connection closed." message is printed.
This code is a simple example and can be further modified and expanded. It serves to create your own application for measurement and automation.