Отправка данных UDP через C# Winform на STM32 - PullRequest
0 голосов
/ 02 марта 2020

Я хочу отправить данные в массиве, используя UDP

                        send_buffer[0] = 10;
                        send_buffer[1] = 'b';
                        udpsend(send_buffer);

Это то, что я пытался

        string [] send_msg1 ;
        send_msg1 = new string[20];
        send_msg1[0] = " 't' ";
        send_msg1[1] = " 8 ";

        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPAddress broadcast = IPAddress.Parse("192.168.1.4");
        IPEndPoint ep = new IPEndPoint(broadcast, 80);



        byte[]  sendbuf1 = Encoding.Unicode.GetBytes(send_msg1); // getting error here
        s.SendTo(sendbuf1, ep);

Этот код выше не отправляется в виде массива.

1 Ответ

0 голосов
/ 03 марта 2020

Похоже, что вы отправляете данные с использованием udp.

Я создаю пример кода, который может успешно отправлять и получать данные.

Код:

Сервер :

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UdpClient udpServer = new UdpClient(11000);

            while (true)
            {
                var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
                var data = udpServer.Receive(ref remoteEP);
                Byte[] sendBytes = Encoding.ASCII.GetBytes(textBox1.Text);
                udpServer.Send(sendBytes, sendBytes.Length, remoteEP); // if data is received reply letting the client know that we got his data          
            }
        }
    }

Клиент:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var client = new UdpClient();
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening
            client.Connect(ep);

            // send data
            client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5);

            // then receive data
            var receivedData = client.Receive(ref ep);
            string data = Encoding.Default.GetString(receivedData);
            MessageBox.Show("receive data from " + ep.ToString()+"   "+data);

            Console.Read();
        }
    }

Результат:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...