본문 바로가기

C#/Network

C# UDP

C# UDP

 

 

UDP 메세지 보내기

UdpClient udpClient = new UdpClient("127.0.0.1", 11000);
Byte[] sendBytes = Encoding.ASCII.GetBytes("PlayWall1F");
udpClient.Send(sendBytes, sendBytes.Length);
udpClient.Close(); 

 

 

UDP 메세지 마지막에 NewLine 붙여서 보내기

UdpClient udpClient = new UdpClient(ip, port);
Byte[] sendBytes = Encoding.ASCII.GetBytes(message);
 
byte[] newLine = System.Text.ASCIIEncoding.ASCII.GetBytes(Environment.NewLine);
var newbyte = Combine(sendBytes, newLine);
 
udpClient.Send(newbyte, newbyte.Length);
udpClient.Close();

 

 

UDP 메세지 받기

Thread udpThread = new Thread(new ThreadStart(ListenForData));
udpThread.IsBackground = true;
udpThread.Start();
 
private void ListenForData()
{
    listener = new UdpClient(udpPort);
    IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, udpPort);
 
    try
    {
        while (true)
        {
            byte[] bytes = listener.Receive(ref groupEP);
            string message = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
            Debug.WriteLine(message);
            if (message.Contains("power"))
            {
                var msgs = message.Split('|');
                if (msgs.Length == 2)
                {
                    if(msgs[1] == PowerOption.off.ToString())
                    {
                        Process.Start("Shutdown.exe", "-s -f -t 00");
                    }
                    else if (msgs[1] == PowerOption.reboot.ToString())
                    {
                        Process.Start("Shutdown.exe", "-r -f -t 00");
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}