728x90
서버
static void Main(string[] arg)
{
//DNS (Domain Name System) -> www.xxxxx.com
string host = Dns.GetHostName();//host는 goole.com 도메인주소
IPHostEntry ipHost = Dns.GetHostEntry(host);//도메인 주소를 통해 ip획득위해
IPAddress ipAddr = ipHost.AddressList[0];//0번은 ip6, 1번은 ip4
IPEndPoint endPoint = new IPEndPoint(ipAddr, 7777);
//문지기
Socket listenSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
//문지기교육
listenSocket.Bind(endPoint);
//영업시작
//backlog : 최대 대기수
listenSocket.Listen(10);
while (true)
{
Console.WriteLine("Listenning....");
//손님입장
Socket clientSocket = listenSocket.Accept();//블로킹함수이기 때문에 클라이언트가 들어오지 않는다면 안들어온다.
//받는다.
byte[] recvBuff = new byte[1024];
int recvBytes = clientSocket.Receive(recvBuff);//몇개의 리시브 바이트를 받았는지
string recvData = Encoding.UTF8.GetString(recvBuff, 0, recvBytes);
Console.WriteLine($"FromClient : {recvData}");
//보낸다.
byte[] sendBuff = Encoding.UTF8.GetBytes("Welcom");
clientSocket.Send(sendBuff);
//클라이언트 제거
clientSocket.Shutdown(SocketShutdown.Both);//클라이언트에게 끊을 예정이란걸 알려줌
clientSocket.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
클라이언트
static void Main(string[] args)
{
//DNS (Domain Name System) -> www.xxxxx.com
string host = Dns.GetHostName();
IPHostEntry ipHost = Dns.GetHostEntry(host);
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint endPoint = new IPEndPoint(ipAddr, 7777);
//휴대폰설정
Socket socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect(endPoint);
Console.WriteLine($"Connected To {socket.RemoteEndPoint}");
//보낸다.
byte[] sendBuff = Encoding.UTF8.GetBytes("Hellow");
int senbyte = socket.Send(sendBuff);
//받는다
byte[] recvBuff = new byte[1024];
int recvBytes = socket.Receive(recvBuff);
string recvData = Encoding.UTF8.GetString(recvBuff, 0, recvBytes);
Console.WriteLine($"From Server {recvData}");
//나간다
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
728x90
'VisualStudio > C#서버' 카테고리의 다른 글
[C#서버] TCP VS UDP (0) | 2022.10.27 |
---|---|
[C#서버] 블로킹(Accept)와 논블로킹(AcceptAsync) (0) | 2022.10.27 |
[C#서버] TLS(Thread Local Storage) - 쓰레드로컬(ThreadLocal) (0) | 2022.10.26 |
[C#서버][개념] 임계영역 특수락 - ReaderWriterLockSlim 특수상황 Lock 처리 방법 (0) | 2022.10.26 |
[C#서버][개념] 임계영역와 Evnet락 (AutoResetEvent & ManualResetEvent) (0) | 2022.10.26 |