UDP 참고 : UDP - 나무위키 (namu.wiki)
UDP - 나무위키
데이터 신뢰성 문제가 있는 프로토콜이라 우스갯소리로 Unreliable Damn Protocol(믿지 못할 빌어먹을 프로토콜)의 축약어라 부르는 경우도 있다. UDP라는 독자적인 규약으로 떨어져 나오긴 했으나 사
namu.wiki
1. 서버
class Program
{
static void Main(string[] args)
{
Console.WriteLine("UDP Server");
ServerFunc();
}
private static void ServerFunc()
{
// IPv4, 스트림, TCP --> TCP는 스트림으로, UDP는 데이터그램으로
using (Socket svrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
// 어떤 ip이던 9999 포트로 --> 0.0.0.0:9999
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 9999);
svrSocket.Bind(endPoint);
byte[] recvBytes = new byte[1024];
EndPoint cltEP = new IPEndPoint(IPAddress.None, 0);
while (true)
{
int nRecv = svrSocket.ReceiveFrom(recvBytes, ref cltEP); // 받은 문자 바이트
string text = Encoding.UTF8.GetString(recvBytes, 0, nRecv);
Console.WriteLine(text);
byte[] sendBytes = Encoding.UTF8.GetBytes("Hello: " + text); // 전송
svrSocket.SendTo(sendBytes, cltEP);
}
}
}
}
2. 클라이언트
class Program
{
static void Main(string[] args)
{
Console.WriteLine("UDP Client");
ClientFunc();
}
private static void ClientFunc()
{
using (Socket cltSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
EndPoint ServerPoint = new IPEndPoint(IPAddress.Loopback, 9999);
EndPoint SendPoint = new IPEndPoint(IPAddress.None, 0);
byte[] sendByte = Encoding.UTF8.GetBytes("I'm udp client");
cltSocket.SendTo(sendByte,ServerPoint);
byte[] recvBytes = new byte[1024];
int nRecv = cltSocket.ReceiveFrom(recvBytes, ref SendPoint);
string text = Encoding.UTF8.GetString(recvBytes, 0, nRecv);
Console.WriteLine(text);
cltSocket.Close(); // 세션 종료
}
}
}
'C#' 카테고리의 다른 글
[C#] gRPC 와 LiteDB 사용 (0) | 2020.12.15 |
---|---|
[C#] TCP Listener을 이용한 비동기 (2) | 2020.12.04 |
[C#] TCP Socket을 이용한 통신 (0) | 2020.12.04 |
[C#] 8.0 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용 (0) | 2020.12.01 |
[C#] BCL DataContractJsonSerializer을 이용한 객체 JSON 직렬화 (0) | 2020.11.30 |