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);
    }
}
'C# > Network' 카테고리의 다른 글
| C# Multi Thread TcpServer (0) | 2020.08.14 | 
|---|---|
| C# TCPServer with WebSocket (0) | 2020.08.13 | 
| C# WOL 컴퓨터 원격 온오프 (0) | 2020.08.07 | 
| C# Ping 테스트, 해당 IP 장치 이름 가져오기 (0) | 2020.08.07 | 
| C# 네트워크 상 맥어드레스 가져오기 (0) | 2020.08.07 |