728x90

소켓 통신 실행 흐름과 구조

 

"TCPListener 서버 1단계" 구현 목표 

 

C# 윈폼 프로젝트 생성하기

 

C# 라이브러리 생성하기

 

C# 라이브러리에 Server 구현하기

더보기
라이브러리 프로젝트가 생성되면, Class1.cs 클래스 파일명을 변경
모든 참조 일괄 변경

 

IPAddress? mIP;
int mPort;
TcpListener? mTCPListener;

public async Task StartServerListeningAsync(IPAddress? ipaddr = null, int port = 23000)
{
    if (ipaddr == null)
        ipaddr = IPAddress.Loopback; // Default to localhost

    if (port <= 0 || mPort > 65535)
        port = 23000; // Default port

    mIP = ipaddr;
    mPort = port;

    //(1)
    mTCPListener = new TcpListener(mIP, mPort);

    //(2)
    mTCPListener.Start();
    Console.WriteLine($"Server started on {mIP.ToString()}:{mPort}");

    //(3)
    TcpClient client = await mTCPListener.AcceptTcpClientAsync();
    Console.WriteLine("Client connected.");
}
모두 한 번 동작하고, 프로그램이 종료된다.

 

동기 로직을 async/await 비동기 로직으로

더보기
동기화 함수와 로직으로 Accept 동작에서 블록된다. 아래 비동기 로직 구현과 비교한다.
상태 머신(State Machine)으로 스레드를 블록하지 않고 , 비동기(Async) 작업(Task) 완료를 기다림(await)

 


 

내 프로젝트에 C# 라이브러리 참조하기


C# 윈폼 버튼에 라이브러리 사용하기 

: TCPListener (1), (2), (3) 

더보기

 


 

BtnAcceptIncomingAsync_Click 버튼 이벤트명 변경
라이브러리에 구현한 클래스 서버 객체 생성
“Form1 생성자 실행 시점에 TCPSocketServer 객체를 동적으로 생성하여 초기화합니다.

 

실행 테스트

더보기

 

 

이해: UI 동작 쓰레드와, TCP Server 의 Accept( ) 동작이 비동기로 처리되는 점을 비교한다..