--에코서버--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//추가한 네임스페이스
using System.Net;
using System.Net.Sockets;
namespace UdpEchoServer
{
class Program
{
//포트번호
const int ServerPortNumber = 5432;
static void Main(string[] args)
{
try
{
//UDP Socket 만들기
Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
// udpSocket.SetSocketOption(SocketOptionLevel.Socket,
// SocketOptionName.UseLoopback, true);
//소켓에 종단점 연결
EndPoint localEP = new IPEndPoint(IPAddress.Any, ServerPortNumber);
//원격 호스트의 종단점을 얻어오기 위한 임시 중단점
EndPoint remoteEP = new IPEndPoint(IPAddress.None, ServerPortNumber);
//소켓에 중단점 바인딩
udpSocket.Bind(localEP);
//받기 위한 버퍼 설정
byte[] receiveBuffer = new byte[512];
try
{
while (true)
{
receiveBuffer = new byte[512];
//데이터를 버퍼에 받아오며, 원격 호스트의 종단점을 알아온다.
int receivedSize = udpSocket.ReceiveFrom(receiveBuffer,
ref remoteEP);
string temp = Encoding.UTF8.GetString(receiveBuffer);
string temp2 ="";
temp2 = temp.Substring(0, receivedSize);
Console.WriteLine(temp2);
//바로 데이터를 보냄
udpSocket.SendTo(receiveBuffer,
receivedSize, SocketFlags.None, remoteEP);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
udpSocket.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
--에코 클라이언트--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//추가한 네임스페이스
using System.Net;
using System.Net.Sockets;
namespace UdpEchoClient
{
class Program
{
const int ServerPortNumber = 5432;
static void Main(string[] args)
{
try
{
//UDP소켓 생성
Socket udpSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram , ProtocolType.Udp);
//소켓에 종단점 연결
EndPoint localEP = new IPEndPoint(IPAddress.Any, 0);
//임시적으로 루프백 사용
EndPoint remoteEP = new IPEndPoint(IPAddress.Loopback,
ServerPortNumber);
//바인딩
udpSocket.Bind(localEP);
string temp = "";
while (temp != "exit")//데이터 전송
{
byte[] sendBuffer;
Console.Write("전송할 데이터 입력 : ");
temp = Console.ReadLine();
sendBuffer = Encoding.UTF8.GetBytes(temp);
//소켓을 이용해 서버로 문자열을 보낸다.
udpSocket.SendTo(sendBuffer, remoteEP);
//데이터 수신
byte[] receiveBuffer = new byte[512];
int receiveSize = udpSocket.ReceiveFrom(receiveBuffer,
ref remoteEP);
//받아온 내용을 화면에 출력
Console.WriteLine(Encoding.UTF8.GetString(receiveBuffer, 0,
receiveSize));
}
udpSocket.Close();
}
catch(SocketException se)
{
Console.WriteLine(se.ToString());
}
}
}
}
'프로그래밍' 카테고리의 다른 글
[C#]TCP 에코 서버 클라이언트 예제 (0) | 2009.01.15 |
---|---|
[C#]인코딩예제 (0) | 2009.01.15 |
DTD 규칙 (0) | 2009.01.09 |
Vaild XML 문서란 - DTD에 대한 필요성 (0) | 2009.01.09 |
XML의 네임스페이스 (0) | 2008.12.31 |
댓글