Tcp 비동기 채팅 프로그램 with Console
Async Tcp Chat
Tcp 비동기 채팅 프로그램 with Console
목표 구조
- TCP 기반 1:1 채팅 (콘솔)
- 서버: 다수 클라이언트 수용
- 클라이언트: 서버 접속 후 실시간 채팅
- 모든 통신은
async/await
로 구현 (UI 확장 고려) - 메시지 송수신은 UTF-8
서버 코드 (Async TCP 서버)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// TcpChatServer.cs
using System.Net;
using System.Net.Sockets;
using System.Text;
class TcpChatServer
{
static async Task Main()
{
TcpListener listener = new TcpListener(IPAddress.Any, 9000);
listener.Start();
Console.WriteLine("서버 시작됨. 클라이언트 기다리는 중...");
while (true)
{
TcpClient client = await listener.AcceptTcpClientAsync();
Console.WriteLine("클라이언트 접속됨");
_ = HandleClientAsync(client);
}
}
static async Task HandleClientAsync(TcpClient client)
{
var stream = client.GetStream();
byte[] buffer = new byte[1024];
while (true)
{
int byteCount = await stream.ReadAsync(buffer, 0, buffer.Length);
if (byteCount == 0) break;
string message = Encoding.UTF8.GetString(buffer, 0, byteCount);
Console.WriteLine($"클라이언트: {message}");
string response = $"[서버]: {message}";
byte[] responseData = Encoding.UTF8.GetBytes(response);
await stream.WriteAsync(responseData, 0, responseData.Length);
}
Console.WriteLine("클라이언트 연결 종료");
client.Close();
}
}
클라이언트 코드 (Async TCP 클라이언트)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// TcpChatClient.cs
using System.Net.Sockets;
using System.Text;
class TcpChatClient
{
static async Task Main()
{
TcpClient client = new TcpClient();
await client.ConnectAsync("127.0.0.1", 9000);
Console.WriteLine("서버에 연결됨");
var stream = client.GetStream();
_ = Task.Run(async () =>
{
byte[] buffer = new byte[1024];
while (true)
{
int byteCount = await stream.ReadAsync(buffer, 0, buffer.Length);
if (byteCount == 0) break;
string message = Encoding.UTF8.GetString(buffer, 0, byteCount);
Console.WriteLine(message);
}
});
while (true)
{
string? input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input)) continue;
byte[] data = Encoding.UTF8.GetBytes(input);
await stream.WriteAsync(data, 0, data.Length);
}
}
}
실행 방법
- 서버 먼저 실행
- 클라이언트 실행
- 여러 클라이언트도 접속 가능
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.