C#

C# UdpClient 통신하기 (Server 예제 포함)

sheepone 2022. 10. 7. 18:03
반응형

자신의 IP로 셋팅후 V전송시 V를 받은 사진

 

UDP CLIENT

using System;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp8
{

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

            tbIpaddress.Text = CONFIG.IPADDRESS;
            tbPort     .Text = CONFIG.PORT     ;
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            CONFIG.IPADDRESS = tbIpaddress.Text ;
            CONFIG.PORT      = tbPort     .Text ;
        }

        private void btSend_Click(object sender, EventArgs e)
        {
            string sData    = tbSend.Text;
            string sRecieve = UDP.Ins.SendMsg(sData + "\r");
            //lstData.Items.Add(sResult);
            lstData.Items.Insert(0,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " => " + sRecieve);
            lstData.EnsureVisible(0);
        }    
    }

    public class CONFIG
    {
        public static string IPADDRESS { 
            get { return ConfigurationManager.AppSettings.Get("IPADDRESS"); }
            set { Configuration Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                  Config.AppSettings.Settings.Remove("IPADDRESS");
                  Config.AppSettings.Settings.Add   ("IPADDRESS",value); 
                  Config.Save(ConfigurationSaveMode.Modified);
                  ConfigurationManager.RefreshSection(Config.AppSettings.SectionInformation.Name);
            }
        }
        public static string PORT      { 
            get { return ConfigurationManager.AppSettings.Get("PORT"); }
            set { Configuration Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                  Config.AppSettings.Settings.Remove("PORT");
                  Config.AppSettings.Settings.Add   ("PORT",value);
                  Config.Save(ConfigurationSaveMode.Modified);
                  ConfigurationManager.RefreshSection(Config.AppSettings.SectionInformation.Name);
            }
        }
    }

    public class UDP
    {
        public static UDP Ins
        {
            get { return ins == null ? (ins = new UDP()) : ins; }
        }
        private static UDP ins = null;

        UdpClient udpClient;

        public UDP() { }

        public string SendMsg(string _sMsg)
        {
            string sRst = "";

            udpClient = new UdpClient(Int32.Parse(CONFIG.PORT));
            udpClient.Client.SendTimeout    = 1000;
            udpClient.Client.ReceiveTimeout = 1000;
            udpClient.EnableBroadcast = true;

            //udpClient.
            byte[] datagram = Encoding.UTF8.GetBytes(_sMsg);
            udpClient.Send(datagram, datagram.Length, CONFIG.IPADDRESS, Int32.Parse(CONFIG.PORT));

            //BeginReceive
            var timeToWait = TimeSpan.FromMilliseconds(100);
            var asyncResult = udpClient.BeginReceive( null, null );
            asyncResult.AsyncWaitHandle.WaitOne( timeToWait );
            if (asyncResult.IsCompleted)
            {
                try
                {
                    IPEndPoint remoteEP = null;
                    byte[] receivedData = udpClient.EndReceive( asyncResult, ref remoteEP );
                    string sMsg   = Encoding.Default.GetString(receivedData);
                    string sData  = sMsg.Substring(0, sMsg.IndexOf("\r"));
                    sRst = sData;
                }
                catch (Exception ex)
                {
                }
            } 
            else
            {
                // The operation wasn't completed before the timeout and we're off the hook
            }
            udpClient.Close(); 

            return sRst;
        }
    }
}

 

SERVER로 사용할때

        //서버로 사용할때
        // (1) UdpClient 객체 성성. 포트 7777 에서 Listening
        UdpClient srv = new UdpClient(3771);
        
        // 클라이언트 IP를 담을 변수
        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.70.10"), 0);
        
        while(true)
        {
            // (2) 데이타 수신
            byte[] dgram = srv.Receive(ref remoteEP);
            Debug.WriteLine("[Receive] {0} 로부터 {1} 바이트 수신", remoteEP.ToString(), dgram.Length);
            
            string sData = Encoding.Default.GetString(dgram);
            Debug.WriteLine(sData);
        
            // (3) 데이타 송신
            srv.Send(dgram, dgram.Length, remoteEP);
            Debug.WriteLine("[Send] {0} 로 {1} 바이트 송신", remoteEP.ToString(), dgram.Length);
        }

 

예제 파일첨부

Client.zip
0.16MB

 

반응형