728x90


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

 

클라이언트 관리 구현

더보기
List<TcpClient> mClients;

public TCPSocketServer()
{
    mClients = new List<TcpClient>();
}

 

 

//연결될 때마다 서버-클라 동작해야 할 로직
mClients.Add(client);
Console.WriteLine(
    string.Format("클라이언트 연결 완료 (총 연결 수: {0}) - 원격 주소: {1}",
    mClients.Count, client.Client.RemoteEndPoint)
    );

 

9

if (mClients.Contains(client))
{
    mClients.Remove(client);
    Debug.WriteLine(
        String.Format("클라이언트 연결 종료, 총 연결 수: {0}", mClients.Count));
}

 

클라이언트 메시지 전송 구현

더보기
async 없이 동작 하지만, 비동기 호출 결과를 기다리지 않기 때문에, 실제 데이터가 모두 전송되기 전에 함수가 종료될 수도 있다.

 

public async Task SendToAll(string Msg)
{
    if (string.IsNullOrEmpty(Msg))
    { 
        return; 
    }

    try
    {
        byte[] buffMessage = Encoding.ASCII.GetBytes(Msg);

        foreach (TcpClient clnt in mClients)
        {
            //(6)
            await clnt.GetStream().WriteAsync(buffMessage, 0, buffMessage.Length);
        }
    }
    catch (Exception excp)
    {
        Console.WriteLine($"전송 중 오류 발생: {excp.Message}");
    }
}

 

버튼으로 전송

더보기
// 기다리지 않아도 된다면 async를 생략해도 됩니다.
private void BtnSendAll_Click(object sender, System.EventArgs e)
{
    // _는 Discard(버림값) 리턴값이 필요 없는 모든 상황에서 값을 사용하지 않을 의도 명시
    _ = mServer.SendToAll(textBox1.Text.Trim());
}