using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UdpClient
{
class Program
{
static void Main(string[] args)
{
// UDP용 소켓 생성
UdpClient client = new UdpClient();
// 보낼 데이터 인코딩해서 배열에 담기
string msg = "안녕하세용!";
byte[] datagram = Encoding.UTF8.GetBytes(msg);
// 2. 데이타 송신
// ip 주소와 포트번호 특정해서 데이터 송신
client.Send(datagram, datagram.Length, "127.0.0.1", 7777);
Console.WriteLine("[Send] 127.0.0.1 로 {0} 바이트 전송", datagram.Length);
// 3. 데이타 수신
// Endpoint 객체 생성하고 그 Endpoint에 들어오는 데이터 수신
IPEndPoint epRemote = new IPEndPoint(IPAddress.Any, 0);
byte[] bytes = client.Receive(ref epRemote);
Console.WriteLine("[Receive] {0} 로 부터 {1} 바이트 수신", epRemote, bytes.Length);
// 4. UdpClient 객체 닫기
client.Close();
}
}
}
<aside> 🐿️ UDP 서버는 통상 UDP 포트를 Listening 하고 있으면서 루프 안에서 계속 데이터 송수신을 처리한다
</aside>