How to send and receive commands from a UDP network server via .NET Core console application

独自空忆成欢 提交于 2019-12-11 16:46:09

问题


First off, I'm sorry if there is a solution for this problem already.

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.

Any suggestions would be helpful. I haven't worked with anything related to UDP ip clients and servers before and this is my first attempt.

[4/22/19]

I created 2 console apps this time around.

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.

来源:https://stackoverflow.com/questions/55767920/how-to-send-and-receive-commands-from-a-udp-network-server-via-net-core-console

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!