개발자이야기/C#

[C#] C#으로 작성한 비동기 채팅 프로그램 예제

퐈니스타일 2023. 8. 7. 09:00

 

안녕하세요. 오늘은 지난번 C# 소켓통신 포스팅 글에 이어 C#으로 작성된 비동기 채팅 프로그램을 간단한 예제와 함께 알아보겠습니다.

 

이 포스팅에서는 C#으로 작성한 비동기 채팅 프로그램 예제를 제공합니다. 이번 예제를 통해 TCP/IP 네트워크 연결과 비동기 처리를 이용하여 채팅 프로그램을 구현하는 방법에 대해 알아볼 수 있습니다

 

지난번 포스팅은 아래 링크로 소켓통신의 기본

 

C# 소켓통신의 기본

C#에서 소켓 통신을 하기 위해서는 System.Net.Sockets 네임스페이스를 사용해야 합니다. 1. 서버 구현하기 서버를 구현하기 위해서는 TcpListener 클래스를 사용합니다. TcpListener 클래스는 클라이언트의

hwanistyle.tistory.com

C#은 비동기 코딩을 지원하는 강력한 언어입니다. 그리고 TCP/IP 연결도 용이하게 할 수 있습니다. 이번 예제를 통해 C#을 이용하여 비동기 채팅 프로그램을 어떻게 만드는지 살펴보겠습니다.

비동기 채팅 프로그램은 사용자들이 서로 채팅을 할 수 있는 애플리케이션으로, 클라이언트와 서버 사이에서 비동기적으로 메시지를 주고받을 수 있습니다.

 

C#에서 제공하는 System.Net.Sockets, System.Text, System.Threading 등의 라이브러리를 이용하여 이 예제를 작성할 것입니다.

System.Net.Sockets: TCP/IP 네트워크 연결에 대한 클래스를 제공합니다.
System.Text: 문자열 인코딩 및 디코딩을 지원합니다.
System.Threading: 비동기 처리를 위한 클래스를 제공합니다.

먼저, 서버 측 구현부터 작성해보겠습니다.

 

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

namespace Server
{
    class Program
    {
        static TcpListener server = new TcpListener(IPAddress.Any, 12345);
        static void Main(string[] args)
        {
            server.Start();
            Console.WriteLine("서버가 시작되었습니다.");

            while (true)
            {
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("클라이언트가 연결되었습니다.");

                Thread thread = new Thread(() => DoChat(client));
                thread.Start();
            }
        }

        static void DoChat(TcpClient client)
        {
            NetworkStream stream = client.GetStream();
            byte[] buffer = new byte[1024];
            int bytes = 0;
            while (true)
            {
                bytes = stream.Read(buffer, 0, buffer.Length);
                string message = Encoding.Unicode.GetString(buffer, 0, bytes);

                byte[] sendBuffer = Encoding.Unicode.GetBytes(message);
                foreach (TcpClient c in clients)
                {
                    if (c == null) continue;
                    NetworkStream s = c.GetStream();
                    s.Write(sendBuffer, 0, sendBuffer.Length);
                }
            }
        }
    }
}

이 코드에서는 TcpListener 클래스를 사용하여 클라이언트의 연결을 수신 대기합니다. DoChat 메서드는 새로운 클라이언트가 연결될 때마다 새로운 스레드에서 실행됩니다. 이 메서드는 해당 클라이언트에서 읽은 메시지를 콘솔에 출력한 후, 다른 모든 클라이언트에게 메시지를 전송합니다.

이제 클라이언트 측 구현부를 살펴보겠습니다. 

 

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

namespace Client
{
    class Program
    {
        static string name;
        static TcpClient client = new TcpClient();
        static void Main(string[] args)
        {
            Console.Write("닉네임을 입력하세요: ");
            name = Console.ReadLine();
            client.Connect("localhost", 12345);
            Console.WriteLine("서버에 연결되었습니다.");

            NetworkStream stream = client.GetStream();
            byte[] buffer = Encoding.Unicode.GetBytes(name);
            stream.Write(buffer, 0, buffer.Length);

            while (true)
            {
                buffer = new byte[1024];
                int bytes = stream.Read(buffer, 0, buffer.Length);
                string message = Encoding.Unicode.GetString(buffer, 0, bytes);
                Console.WriteLine(message);
            }
        }
    }
}

클라이언트는 사용자의 닉네임을 받은 후, 서버에 연결합니다. 연결이 성공하면, 해당 클라이언트에서는 메시지를 계속 읽고 사용자에게 출력합니다.


이번 포스팅에서는 C#으로 작성한 비동기 채팅 프로그램 예제를 제공했습니다. 이 예제를 통해 C#을 이용하여 TCP/IP 네트워크 연결과 비동기 처리를 이용하여 채팅 프로그램을 구현하는 방법을 알아보았습니다. 

 

감사합니다.

728x90
반응형