본문 바로가기

C#

[C#] Network Programming - Socket Programming(Intro)

네트워크 프로그래밍의 시스템은 식당 운영 방식과 비슷하다.

 

손님과 식당의 관점으로 나누면

 

손님

1) 핸드폰을 준비한다.

2) 식당 번호로 입장을 문의한다.

휴대폰을 통해 대리인 휴대폰과 통화가 가능하다.

 

식당

1) 문지기를 고용한다.

2) 문지기에게 식당의 정보를 교육시킨다.

3) 영업을 시작한다.

4) 손님을 안내한다.

손님 대리인을 통해 손님과 대화가 가능하다.

 

 

 

 

이를 클라이언트와 서버 관점으로 생각하면 다음과 같다.

 

Client

1) 소켓을 준비한다.

2) 서버 주소로 Connect한다.

소켓을 통해 Session 소켓과 패킷 송수신이 가능하다.

 

Server

1) Listner 소켓(단방향)을 준비한다.

2) Bind한다. (=서버 주소 및 Port를 소켓에 연동한다.)

3) Listen한다.

4) Accept한다.

클라이언트 세션을 통해 손님과 통화가 가능하다.

 

 

▼ ServerCore.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServerCore
{
    class ServerCore
    {

        public static void Main(string[] args)
        {
            //DNS (Domain Name System)
            string host = Dns.GetHostName();
            IPHostEntry ipHost = Dns.GetHostEntry(host);
            IPAddress ipAddr = ipHost.AddressList[0];
            IPEndPoint endPoint = new IPEndPoint(ipAddr, 0127);

            //문지기
            Socket listenSocket = new Socket(endPoint.AddressFamily,SocketType.Stream, ProtocolType.Tcp);


            try
            {
                //문지기 교육
                listenSocket.Bind(endPoint);

                //영업 시작
                //Listen(backlog); backlog: 최대 대기수.
                listenSocket.Listen(10);

                while (true)
                {
                    Console.WriteLine("*** LUCA SERVER IS RUNNING ***\n\n");
                    Console.WriteLine("Listening...");

                    //손님을 입장시킨다.
                    Socket clientSocket = listenSocket.Accept();
                    //손님이 오지 않을 경우 무한 대기...


                    //받는다.
                    byte[] receiveBuff = new byte[1024];
                    int receiveBytes = clientSocket.Receive(receiveBuff);
                    string receiveData = Encoding.UTF8.GetString(receiveBuff, 0, receiveBytes);
                    Console.WriteLine($"[From Client] {receiveData}");

                    //보낸다.
                    byte[] sendBuff = Encoding.UTF8.GetBytes("Welcome to MMORPG server !!");
                    clientSocket.Send(sendBuff);

                    //쫓아낸다.
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();

                }
            }

            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }
            
        }
    }
}

 

 

 

▼ DummyClient.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DummyClient
{
    class DummyClient
    {
       
        static void Main(string[] args)
        {
            //서버와 동일한 부분임.
            //DNS (Domain Name System)
            string host = Dns.GetHostName();
            IPHostEntry ipHost = Dns.GetHostEntry(host);
            IPAddress ipAddr = ipHost.AddressList[0];
            IPEndPoint endPoint = new IPEndPoint(ipAddr, 0127);

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


            try
            {
                //문지기한테 입장 문의
                socket.Connect(endPoint); //endPoint(상대방 주소)와 연락 가능한지 묻기
                Console.WriteLine($"Connected to {socket.RemoteEndPoint.ToString()}");

                //보낸다
                byte[] sendBuff = Encoding.UTF8.GetBytes("Hello world!");
                int sentBytes = socket.Send(sendBuff);

                //받는다
                byte[] receiveBuff = new byte[1024];
                int receiveBytes = socket.Receive(receiveBuff);
                string receiveData = Encoding.UTF8.GetString(receiveBuff, 0, receiveBytes);
                Console.WriteLine($"[From Server] {receiveData}");

                //나간다
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();

            }

            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }

        }
    }
}

 

 

 

 

오류 발생:

System.Net.Sockets.SocketException (0x80004005): 액세스 권한에 의해 숨겨진 소켓에 액세스를 시도했습니다 [fe80::261e:ccfd:71bd:fc5e%5]:127

백신 네트워크 침입 차단 사용 해제 + IP 주소 관련 체크표시 해제 + 개인 방화벽 해제 ▶ 해결됨

 

 

실행 결과