C#) C# WPF TCP/IP 메세지 전송

2024. 11. 26. 20:48·LAB/C#

 

 

WPF 를 이용한 TCP/IP 연결 메세지 송수신

출처 입력

[Server]

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace First_wpf
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private TcpListener _server;
        private Thread _listenerThread;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void StartServerButton_Click(object sender, RoutedEventArgs e)
        {
            StartServer();
        }

        private void StartServer()
        {
            _listenerThread = new Thread(() =>
            {
                try
                {
                    _server = new TcpListener(IPAddress.Any, 12345);
                    _server.Start();

                    Dispatcher.Invoke(() => LogTextBox.AppendText("서버 시작됨\n"));

                    while (true)
                    {
                        TcpClient client = _server.AcceptTcpClient();
                        Dispatcher.Invoke(() => LogTextBox.AppendText("클라이언트 연결됨\n"));

                        Thread clientThread = new Thread(() =>
                        {
                            NetworkStream stream = client.GetStream();
                            byte[] buffer = new byte[1024];
                            int bytesRead;

                            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                                Dispatcher.Invoke(() => LogTextBox.AppendText($"수신: {message}\n"));
                            }

                            Dispatcher.Invoke(() => LogTextBox.AppendText("클라이언트 연결 종료\n"));
                            client.Close();
                        });

                        clientThread.Start();
                    }
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() => LogTextBox.AppendText($"오류: {ex.Message}\n"));
                }
            });

            _listenerThread.IsBackground = true;
            _listenerThread.Start();
        }
    }
}
 

=> TcpListener: 클라이언트 연결을 수락하는 서버 역할을 담당

=> AcceptTcpClient: 클라이언트 연결을 기다리고, 연결이 이루어지면 클라이언트를 반환

=>Dispatcher.Invoke: UI 업데이트는 반드시 메인 스레드에서 수행해야 하므로 Dispatcher를 사용해 로그를 업데이트

=>_stream.Write(buffer, 0, buffer.Length) : 메세지 전송

=>_stream.Read(buffer, 0, buffer.Length) : 메세지 수신

=>client.Close() : 클라이언트 소켓 닫기

 

<Window> </Window> 생략 한 Xaml

 <Grid Margin="10">
     <Grid.RowDefinitions>
         <RowDefinition Height="*" />
         <RowDefinition Height="Auto" />
     </Grid.RowDefinitions>

     <!-- 로그 출력 -->
     <TextBox x:Name="LogTextBox" Grid.Row="0" Margin="0,0,0,10" 
              VerticalScrollBarVisibility="Auto" IsReadOnly="True" />

     <!-- 시작 버튼 -->
     <Button x:Name="StartServerButton" Grid.Row="1" Height="30" Content="서버 시작" 
             Click="StartServerButton_Click" />
 </Grid>
 
대표사진 삭제

사진 설명을 입력하세요.

[Client]

using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace First_wpf_clie
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private TcpClient _client;
        private NetworkStream _stream;
        private Thread _listenerThread;
        public MainWindow()
        {
            InitializeComponent();
            ConnectToServer();
        }
        private void ConnectToServer()
        {
            try
            {
                _client = new TcpClient("127.0.0.1", 12345);
                _stream = _client.GetStream();

                LogTextBox.AppendText("서버에 연결됨\n");

                _listenerThread = new Thread(() =>
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead;

                    while ((bytesRead = _stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                        Dispatcher.Invoke(() => LogTextBox.AppendText($"수신: {message}\n"));
                    }
                });

                _listenerThread.IsBackground = true;
                _listenerThread.Start();
            }
            catch (Exception ex)
            {
                LogTextBox.AppendText($"오류: {ex.Message}\n");
            }
        }

        private void SendButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string message = MessageTextBox.Text;
                byte[] buffer = Encoding.UTF8.GetBytes(message);

                _stream.Write(buffer, 0, buffer.Length);
                LogTextBox.AppendText($"전송: {message}\n");

                MessageTextBox.Clear();
            }
            catch (Exception ex)
            {
                LogTextBox.AppendText($"오류: {ex.Message}\n");
            }
        }
    }
}
 

=> _listenerThread = new Thread(() => : 서버로 부터 메세지 수신 하기 위한 스레드 생성

=>TcpClient: 서버와 연결하여 데이터를 송수신

=>GetStream: 데이터를 송수신할 스트림 (메세지를 UTF-8로 인코딩 변환하여 송수신)

=>_stream.Write(buffer, 0, buffer.Length) : 메세지 전송

=>_stream.Read(buffer, 0, buffer.Length) : 메세지 수신

=>MessageTextBox.Clear(); : 입력상자 초기화

 

 

<Window> </Window> 생략 한 Xaml

 <Grid Margin="10">
     <Grid.RowDefinitions>
         <RowDefinition Height="*" />
         <RowDefinition Height="Auto" />
         <RowDefinition Height="Auto" />
     </Grid.RowDefinitions>

     <!-- 로그 출력 -->
     <TextBox x:Name="LogTextBox" Grid.Row="0" Margin="0,0,0,10" 
              VerticalScrollBarVisibility="Auto" IsReadOnly="True" />

     <!-- 메시지 입력 -->
     <TextBox x:Name="MessageTextBox" Grid.Row="1" Height="30" Margin="0,0,0,10" />

     <!-- 전송 버튼 -->
     <Button x:Name="SendButton" Grid.Row="2" Height="30" Content="메시지 전송" 
             Click="SendButton_Click" />
 </Grid>
 

 

'LAB > C#' 카테고리의 다른 글

C# - MVVM 패턴 ICommand  (0) 2024.12.06
MVVM 패턴 - Accuweather API 기반 날씨 검색 APP  (1) 2024.12.02
C# ) C# 기초 (스레드 , 태스크 ,네트워크 프로그래밍)  (0) 2024.11.02
C# ) C# 기초 5 (대리자, 이벤트)  (0) 2024.11.01
C# ) C# 기초 4 (일반화 프로그래밍, 예외처리)  (0) 2024.11.01
'LAB/C#' 카테고리의 다른 글
  • C# - MVVM 패턴 ICommand
  • MVVM 패턴 - Accuweather API 기반 날씨 검색 APP
  • C# ) C# 기초 (스레드 , 태스크 ,네트워크 프로그래밍)
  • C# ) C# 기초 5 (대리자, 이벤트)
it-lab-0130
it-lab-0130
it-lab-0130 님의 블로그 입니다.
  • it-lab-0130
    빠냐냐~
    it-lab-0130
  • 전체
    오늘
    어제
    • 분류 전체보기 (69)
      • 개인 (2)
        • 개발TIP Program (2)
      • LAB (47)
        • Python (5)
        • C (13)
        • TCP_IP (7)
        • C++ (9)
        • QT_C++ (4)
        • C# (9)
      • Project (0)
        • 오류 모음 (0)
        • Python (0)
        • C 와 TCP_IP소켓 (0)
        • C++ (0)
      • Study_ (17)
        • 예제_문제풀이 (10)
        • 학습일지 (7)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • Python
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
it-lab-0130
C#) C# WPF TCP/IP 메세지 전송
상단으로

티스토리툴바