using System;
// .NET 네트워크 네임스페이스
using System.Net;
// .NET 소켓 네임스페이스
using System.Net.Sockets;
// 1) Encoding.ASCII를 사용하기 위한 .NET 텍스트 네임 스페이스
using System.Text;
namespace UdpEchoClient
{
class App
{
// 서버 포트 번호
private const int ServerPortNumber = 5432;
[STAThread]
static void Main(string[] args)
{
try {
// 2) UDP socket을 만든다.
Socket udpSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
// 3) 소켓에 종단점을 연결하자.
// 소켓을 바인드 하기위한 종단점(end point)을 만든다.
EndPoint localEP = new IPEndPoint(
IPAddress.Any, 0);
// 서버의 종단점을 설정한다.
// 테스트용으로 Loopback을 사용할 것이다.
EndPoint remoteEP = new IPEndPoint(
IPAddress.Loopback, ServerPortNumber);
// 소켓에 종단점을 바인드 한다.
udpSocket.Bind(localEP);
// 4) 데이터를 보내자.
// Hello? 문자열을 ASCII로 인코딩하여 버퍼에 담는다.
byte [] sendBuffer;
sendBuffer = Encoding.ASCII.GetBytes("Hello?");
// 소켓을 이용해 서버로 문자열을 보낸다.
udpSocket.SendTo(sendBuffer, remoteEP);
// 5) 데이터를 받자.
// 받을 버퍼를 만들자.
byte [] receiveBuffer = new byte [512];
// 소켓을 이용해 데이터를 받자.
int receivedSize = udpSocket.ReceiveFrom(receiveBuffer,
ref remoteEP);
// 받아온 내용을 화면에 출력한다.
Console.WriteLine(Encoding.ASCII.GetString(receiveBuffer, 0,
receivedSize));
// 6) 소켓을 닫자.
udpSocket.Close();
} catch (SocketException se) {
// 예외를 처리하자.
Console.WriteLine(se.ToString());
}
}
}
}