[ 소켓 프로그램 실습 기본 예제 ]
- 물리적으로 두 대의 PC를 구할 수 없으므로 아래와 같은 방식으로 구현한다.
using System;
using System.Net.Sockets;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Thread serverThread = new Thread(serverFunc);
serverThread.IsBackground = true;
serverThread.Start();
Thread.Sleep(500); // 소켓 서버용 스레드가 실행될 시간을 주기 위해
Thread clientThread = new Thread(clientFunc);
clientThread.IsBackground = true;
clientThread.Start();
Console.WriteLine("종료하려면 아무키나 누르세요.");
Console.ReadLine();
}
private static void serverFunc(object obj)
{
}
private static void clientFunc(object obj)
{
}
}
|
- 서버 측에서 컴퓨터에 할당된 IP 주소 중에서 어떤 것과 연결될지 결정하는 과정을 바인딩(binding)이라 한다.
- UDP를 사용할 때 Socket의 생성자는 아래와 같이 지정한다.
Socket socket =
new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
[ UDP 예제 ]
- 서버에서는 데이터를 받으면 "Hello:" 접두사를 붙여서 client로 다시 보내주는 역할
- 클라이언트는 1초 간격으로 현재 시간을 서버로 전송하고, 서버로 부터 받은 데이터를 출력한다.
private static void serverFunc(object obj)
{
using (Socket srvSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
IPAddress ipAddress = IPAddress.Parse("0.0.0.0"); // 모든 IP에 대해 바인딩
IPEndPoint endPoint = new IPEndPoint(ipAddress, 10200);
srvSocket.Bind(endPoint);
byte[] receiveBytes = new byte[1024];
EndPoint clientEP = new IPEndPoint(IPAddress.None, 0); // receive할 때 그 client의 EndPoint 정보를 저장
while(true)
{
int nRecv = srvSocket.ReceiveFrom(receiveBytes, ref clientEP);
string txt = Encoding.UTF8.GetString(receiveBytes, 0, nRecv);
byte[] sendBytes = Encoding.UTF8.GetBytes("Hello:" + txt);
// 받은 내용에 "Hello:" 접두사를 붙여서 clientEP로 되돌려 보내준다.
srvSocket.SendTo(sendBytes, clientEP);
}
}
}
private static void clientFunc(object obj)
{
using (Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
EndPoint serverEP = new IPEndPoint(IPAddress.Loopback, 10200);
EndPoint senderEP = new IPEndPoint(IPAddress.None, 0);
int nTimes = 5;
while(nTimes-- > 0)
{
byte[] buf = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
clientSocket.SendTo(buf, serverEP);
byte[] receiveBytes = new byte[2048];
int nRecv = clientSocket.ReceiveFrom(receiveBytes, ref senderEP);
string txt = Encoding.UTF8.GetString(receiveBytes, 0, nRecv);
Console.WriteLine(txt);
Thread.Sleep(1000);
}
}
Console.WriteLine("Client socket closed.");
}
출처 : 시작하세요! C# 7.1 프로그래밍(위키북스, 정성태님 저)
'Programming > C#' 카테고리의 다른 글
| MSSQL Database 연동(2) (0) | 2019.03.11 |
|---|---|
| MSSQL Database 연동(1) (0) | 2019.03.05 |
| app.config (0) | 2019.03.05 |
| [네트워크 프로그래밍] Http 통신 (0) | 2019.03.02 |
| [네트워크 프로그래밍] TCP/IP 예제 (0) | 2019.02.27 |