Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
// include <Stdio.H>와 같이 System 라이브러리 사용 선언.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
using Packet;

namespace WindowsFormsApp16  // Form의 이름
{
    
    public partial class Form1 : Form
    {

        UdpClient Client = new UdpClient(19000); //PORT NUMBER
        Byte[] sendBytes = Encoding.ASCII.GetBytes("Broad");

        string data = " ";

        public Form1()
        {
          InitializeComponent();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            textBox2.SelectionStart = textBox2.Text.Length;
        }

        //버튼 1의 설정
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                UdpClient cli = new UdpClient();

                string msg = "Broad";

                byte[] datagram = Encoding.ASCII.GetBytes(msg);
                cli.Send(datagram, datagram.Length, "192.168.1.100", 19000);

               while(true)
              {
               IPEndPoint epRemote = new IPEndPoint(IPAddress.Any, 0);
               byte[] bytes = cli.Receive(ref epRemote);



               // 계속 데이터를 불러와야함. 
               textBox1.Text = "[Send] 192.168.1.100 로 " + datagram.Length + " 바이트 전송\r\n"
                      + "[Send]" + Encoding.UTF8.GetString(datagram) + "\r\n[receive]" + BitConverter.ToString(bytes);
               }

            }


            catch (Exception ex)
            {
                textBox1.Text += ex.Message.ToString();
            }

        }

        //버튼 2의 설정 지정한 수치 출력
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {

                string str = textBox1.Text;
                string SubStr = str.Substring(161, 4);
                string message = string.Empty;

                textBox2.Text = SubStr;

            }
          
            catch
            {
                string message = string.Empty;
                message = string.Format("check conncet");
                MessageBox.Show(message);
            }
        }

        //버튼 3 클릭시 Broad 를 장비로 전달
        private void button3_Click(object sender, EventArgs e)
        {

            try
            {

                textBox1.Clear();
               
            }


            catch
            {
                string message = string.Empty;
                message = string.Format("check conncet");
                MessageBox.Show(message);
            }
            

        }


            //장비에서 들어온 데이터를 Hex 데이터로 변환

            public static string ToHexString(string str)
            {
            var sb = new StringBuilder();

            var bytes = Encoding.Unicode.GetBytes(str);
            foreach (var t in bytes)
            {
                sb.Append(t.ToString("X2"));
            }

            return sb.ToString(); 
             }


        //UDP IP의 선언 및 String to Hex 데이터 출력 

        void recv(IAsyncResult res)
        {

            //Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp);
            //var ep = new IPEndPoint(IPAddress.Parse("192.168.1.100"), 19000);


            UdpClient Client = new UdpClient(); //PORT NUMBER
            IPEndPoint src_ip = new IPEndPoint(IPAddress.Parse("192.168.1.100"), 19000);
            byte[] received = Client.EndReceive(res, ref src_ip);
            data = Encoding.UTF8.GetString(received);


            
            Byte[] sendBytes = Encoding.ASCII.GetBytes("Broad");

         

            // to avoid cross-threading we use Method Invoker
            this.Invoke(new MethodInvoker(delegate
            {

                textBox1.Clear();
                string str = "";

                for (int i = 0; i < 100; i++)
                {
                    str += ToHexString(data.Substring(i, 1)) + " ";
                }

                textBox1.Text = str;

                string str01 = data.Substring(0, 1); //@
                string str02 = data.Substring(1, 1); //F
               
                if ((str01 == "@") && (str02 == "F"))
                {
                    string strHR = data.Substring(2, 1);
                    Int64 Hr_Data = 0;

                    //label1.Text = Hr_Data.ToString();
                }

                //  Int64 Value = 0;
                //    Value = Convert.ToString(data.Substring(2, 1)), 16);
                //  label1.Text = Value.ToString();

            }));

            Client.BeginReceive(new AsyncCallback(recv), null);
        }


    


        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged_1(object sender, EventArgs e)
        {

        }
    }
}


What I have tried:

I used while loop in this code.
For repeated output to textBox1.

The program stops when I proceed with debugging.
Is there a solution?
Posted
Updated 20-Apr-21 3:32am
v2

I suppose that your method Button1_Click ctches the same-named Event from the Button.
With your While-Loop (While TRUE) you hold your Applicaion all the time in this method.
Your Application is no longer responsible ...
What do you think is the sense of this code-snipped ?
 
Share this answer
 
You cannot use a blocking call in a UI event handler (or any other code on the UI thread) without "freezing" the user interface: if the UI thread is busy waiting for your Receive call to return, then it can't update the display in any way.
And having a "no exit" loop in any UI event handler is going to mess things up properly!

Move all your code - loop included - into a different thread, and free up the UI thread to do what it is intended for : updating the display and interacting with the user!
That has its own complications, because you cannot access in any way any UI controls except from the UI thread - so I'd suggest using the BackgroundWorker Class (System.ComponentModel) | Microsoft Docs[^] which allows progress reporting back to the UI thread - and pass your Textbox data back via the UserState property of the event arguments parameter.
 
Share this answer
 
Comments
Member 15034232 20-Apr-21 4:11am    
thx i try this :)
OriginalGriff 20-Apr-21 4:30am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900