I have a UDP server, which is a scale, that is connected to the network. It is listening to any data being sent to it and response with a data back to the client, depending on what command is sent to it. I was able to test this with YAT, a software used to test serial communication.
Testing UDP Connection on YAT:
I want to create a C# (.NET Core) console application that does the same thing. Basically, I want to connect to the UDP server (scale), send commands to it, and receive the data from it. But it doesn't seem to work at the receiving end.
static void Main(string[] args)
{
var ipAddress = "10.130.12.81";
var portNumber = 2102;
var ipEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), portNumber);
try
{
var client = new UdpClient();
client.Connect(ipEndPoint);
if (client != null)
{
var weigh = "\nW\r";
var data = Encoding.ASCII.GetBytes(weigh);
client.Send(data, data.Length);
var receivedData = client.Receive(ref ipEndPoint);
Console.WriteLine($"Received Data: {receivedData}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
When I run the code, it is able to connect and send the data, but sits idle at the client.Receive line, waiting for a message to be sent.
The second time around, I created 2 console apps:
Sender
static void Main(string[] args)
{
var udpClient = new UdpClient();
var ipEndPoint = new IPEndPoint(IPAddress.Parse(_ipAddress), _port);
udpClient.Connect(ipEndPoint);
var msgSent = Encoding.ASCII.GetBytes("W\n");
udpClient.Send(msgSent, msgSent.Length);
}
Receiver
static void Main(string[] args)
{
var udpServer = new UdpClient(2102);
var ipEndPoint = new IPEndPoint(IPAddress.Any, _port);
var msgReceived = udpServer.Receive(ref ipEndPoint);
Console.Write("received data from: " + ipEndPoint.ToString());
}
I tried to run and send messages several times, but no luck. Not sure if I am missing anything. I'll keep hammering away at this; if this doesn't work I'll try using the Socket class instead of UdpClient.
Receive
. – Lex Li