본문 바로가기
C#

[C#] TCP Socket을 이용한 통신

by Jcoder 2020. 12. 4.

서버와 클라이언트

 

TCP 참고 : TCP - 나무위키 (namu.wiki)

 

TCP - 나무위키

TCP는 전화를 거는 것처럼 상대와 연결을 설정하고 통신을 시작한다. 절차는 아래와 같다. Three Way Handshake 1) 상대에게 통신을 하고 싶다는 메시지를 보낸다. (SYN) 2) 상대는 그 메시지에 대한 응답

namu.wiki

 

1. 서버

   class Program

   {

      static void Main(string[] args)

      {

         Console.WriteLine("Tcp Server");

         ServerFunc();

      }



      private static void ServerFunc()

      {

         // IPv4, 스트림, TCP --> TCP는 스트림으로, UDP는 데이터그램으로

         using (Socket svrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))

         {

            // 어떤 ip이던 9999 포트로 --> 0.0.0.0:9999

            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 9999);

 

            svrSocket.Bind(endPoint);

            svrSocket.Listen(100); // 클리이언트 한계는 100

 

            while (true)

            {

               Socket cltSocket = svrSocket.Accept(); // 클라이언트 허용

 

               byte[] recvBytes = new byte[1024];

 

               int nRecv = cltSocket.Receive(recvBytes); // 받은 문자 바이트

               string text = Encoding.UTF8.GetString(recvBytes, 0, nRecv);

 

               Console.WriteLine(text);

 

               byte[] sendBytes = Encoding.UTF8.GetBytes("Hello: " + text); // 전송

 

               cltSocket.Send(sendBytes);

               cltSocket.Close();

            }

         }

      }

   }

 

2. 클라이언트

   class Program

   {

      static void Main(string[] args)

      {

         Console.WriteLine("Tcp Client");

         ClientFunc();

      }

 

      private static void ClientFunc()

      {

         using (Socket cltSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))

         {

            EndPoint ServerPoint = new IPEndPoint(IPAddress.Loopback, 9999);

 

            cltSocket.Connect(ServerPoint); // 서버와 연결

 

            byte[] sendByte = Encoding.UTF8.GetBytes("I'm client");

 

            cltSocket.Send(sendByte);

 

            byte[] recvBytes = new byte[1024];

            cltSocket.Receive(recvBytes);

 

            string text = Encoding.UTF8.GetString(recvBytes, 0, recvBytes.Length);

            Console.WriteLine(text);

            cltSocket.Close(); // 세션 종료

         }

      }

   }