[server 프로그램 c#] 간단한 TCP/IP client , server 구현

코찔찔이·2023년 10월 18일
0
  1. 로컬에서 간단한 client , server 구현 및 테스트
  2. Dns.GetHostName() 로컬 컴퓨터 이름을 가지고 옴.
  3. ipHost.AddressList 현재 pc에 설저된 ip를 list형태로 가지고 옴.
  4. endPoint ip주소와 포트번호
  5. 소스내 (블로킹 함수)로 기재한 부분은 해당 함수가 실행 될 조건이 되지 않으면 해당 위치에서 실행 가능 할때까지 소스가 흐름이 블로킹 됨.
    예) 서버에서 socket.Accept()를 실행 후 접속되는 클라이언트가 없으면 해당 위치에서 무한정대기.

1. server

using System;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServerCore
{
    class Program
    {
        static void Main(string[] args)
        {
            string host = Dns.GetHostName();
            IPHostEntry ipHost = Dns.GetHostEntry(host);
            IPAddress ipaddr = ipHost.AddressList[0]; //아이피가 여러개 있을수 있으며 배열로 ip를 반환함
            IPEndPoint endPoint = new IPEndPoint(ipaddr, 7777);

            Socket socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(endPoint);

            //최대 연결 개수 정의
            socket.Listen(10);

            while (true)
            {

                try
                {

                    Console.WriteLine("Listening...");
                    //손님입장
                    Socket clientSocket =  socket.Accept();



                    // 받는다.(블로킹 함수)
                    byte[] recvBuff = new byte[1024];
                    int recvBytes = clientSocket.Receive(recvBuff);
                    string recvData = Encoding.UTF8.GetString(recvBuff, 0, recvBytes);
                    Console.WriteLine($"[From Client] {recvData}");

                    //전송 한다.(블로킹 함수)
                    byte[] sendBuffe = Encoding.UTF8.GetBytes("welcome to MMORPG Server !...");
                    clientSocket.Send(sendBuffe);

                    //예고 
                    clientSocket.Shutdown(SocketShutdown.Both);
                    //연결끊기
                    clientSocket.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
}

2. client

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace DummyClient
{
    class Program
    {


        static void Main(string[] args)
        {
            string host = Dns.GetHostName();
            IPHostEntry ipHost = Dns.GetHostEntry(host);
            IPAddress ipaddr = ipHost.AddressList[0]; //아이피가 여러개 있을수 있으며 배열로 ip를 반환함
            IPEndPoint endPoint = new IPEndPoint(ipaddr, 7777);


            try
            {
                //휴대폰 설정(소켓)
                Socket socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                //문지기한테 입장 문의
                //접속 대상의 endPoint를 넣어주면 해당 포인트의 서버가 열려있을경우 접속
                socket.Connect(endPoint);
                Console.WriteLine($"Conneted to {socket.RemoteEndPoint.ToString()}");

                //보낸다.(블로킹 함수) 
                byte[] sendbuff = Encoding.UTF8.GetBytes("Hellow world!");
                int sendByte = 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.Message);
            }
		}
	}	
}

3. 실행 화면

  1. server를 열고 client 연결대기
  2. client에서 접속후 Hellow world!를 전송.
  3. server에서는 client에서 보낸 메시지를 받아 console로 출력
  4. server에서 회신으로 welcome to MMORPG Server !... 을 전송 후 연결 해제.
  5. client에서는 서버에서 보낸 메시지를 받아 console로 출력 후 연결해제
  6. server는 while문으로 다른 client의 접속을 기다리며 , client는 접속 종료 후 프로그램 종료
  • server

  • client

0개의 댓글