기본 콘텐츠로 건너뛰기

[C#][Network][Thread] C#에서 쓰레드를 이용한 에코서버의 기본구조


// Thread Netwotk Server Exam

namespace threadNetworkExam
{
    public partial class Form1 : Form
    {

        // TCP 소켓통신 서버구현을 위해 TCP리스너 정의/초기화
        private TcpListener tcpListner = null;
       
        public Form1()
        {
            InitializeComponent();
        }

        // Thread Method
        // Client 접속시 스레드가 호출하여 작업할 메소드 정의
        private void AcceptClient()
        {
            while (true)
            {
                // Client 소켓통신을 위해 수신을 대기하는 TcpClient 생성
                // TcpListner를 통해 생성
                TcpClient tcpClient = tcpListner.AcceptTcpClient();

                if (tcpClient.Connected)
                {
                    // 접속한 Client IP정보를 얻어서 리스트박스에 추가
                    string str = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
                    listBox1.Items.Add(str);
                }

                EchoServer echoServer = new EchoServer(tcpClient);
                Thread th = new Thread(new ThreadStart(echoServer.Process));
                th.IsBackground = true;
                th.Start();

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            tcpListner = new TcpListener(3000);
            tcpListner.Start();

            // 서버의 IP주소를 얻어서 텍스트박스에 넣는다.
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            for(int i = 0; i < host.AddressList.Length; i++)
            {
                if(host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                {
                    textBox1.Text = host.AddressList[i].ToString();
                    break;
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            tcpListner.Stop();         
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 서버시작 버튼클릭시 클라이언트 접속대기 및 처리를 위한 쓰레드 생성
            // Main 종료시 같이 종료되기위해 백그라운드로 설정
            Thread th = new Thread(new ThreadStart(AcceptClient));
            th.IsBackground = true;
            th.Start();
        }
    }

    public class EchoServer
    {
        TcpClient refClient;
        private BinaryReader br = null;
        private BinaryWriter bw = null;
        int intValue;
        float floatValue;
        string strValue;

        public EchoServer(TcpClient client)
        {
            refClient = client;
        }

        public void Process()
        {
            NetworkStream ns = refClient.GetStream();
            try
            {
                br = new BinaryReader(ns);
                bw = new BinaryWriter(ns);

                while(true)
                {
                    intValue = br.ReadInt32();
                    floatValue = br.ReadSingle();
                    strValue = br.ReadString();

                    bw.Write(intValue);
                    bw.Write(floatValue);
                    bw.Write(strValue);

                }
            }
            catch (SocketException se)
            {
                br.Close();
                bw.Close();
                ns.Close();
                ns = null;
                refClient.Close();
                MessageBox.Show(se.Message);
                Thread.CurrentThread.Abort();
            }
            catch (IOException ex)
            {
                // 연결이 끊어져 읽을 수 없을떄.
                br.Close();
                bw.Close();
                ns.Close();
                ns = null;
                refClient.Close();
                MessageBox.Show(ex.Message);
                Thread.CurrentThread.Abort();
            }
        }
    }
}



이 블로그의 인기 게시물

[C#] 연산자 목록(Operators)

[C#] C# 프로그램의 일반적인 구조(A skeleton of a C# program)

// A skeleton of a C# program  using System; namespace YourNamespace {     class YourClass     {     }     struct YourStruct     {     }     interface IYourInterface      {     }     delegate int YourDelegate();     enum YourEnum      {     }     namespace YourNestedNamespace     {         struct YourStruct          {         }     }     class YourMainClass     {         static void Main(string[] args)          {             //Your program starts here...         }     } } By Microsoft.MSDN :: .NET Guide Docs

[C#] .NET Configuration file :: App.config

프로그램의 옵션들을 담아 두는 파일로서 아주 예전에는 .INI 파일을 사용하였었으며, 이후 윈도우즈가 관리하는 레지스트리 데이타베이스에 시스템 및 응용프로그램의 옵션들을 저장하였다. 레지스트리는 프로그램의 옵션을 저장하는 훌륭한 저장 장소이나, 모든 응용프로그램이 항상 레지스트리에 데이타를 쓰는 권한을 갖는 것은 아니였기 때문에 Permission 제약점이 있었다. .NET Framework에서는 프로그램의 행위를 결정짓는 옵션들을 저장하기 위해 .Config 파일을 사용한다. 데스크탑 응용프로그램 .EXE 에 대해서 Configuration 파일(구성파일)은 .EXE.Config이 되는데, 예를 들어, TEST.EXE의 구성 파일은 TEST.EXE.Config가 된다. Visual Studio에서 콘솔, 윈폼, 혹은 WPF 등의  데스크탑 프로젝트를 생성한 후 App.config 파일을 추가하고(아래 그림처럼 Application Configuration File 추가) 여기에 필요한 옵션들을 설정한 후 빌드하면 .EXE 파일에 대한 .EXE.Config 파일이 자동으로 생성 된다. 그리고 이렇게 추가한 App.config 파일의 내용을 소스코드에서 사용하기위해서는 "참조"에서 '참조 추가하기'를 통해 반드시 에셈블리의 "System.Configurarion"을 추가하고 사용 할 소스코드에 using 문으로 추가해 주어야 한다.  " using System.Configuration; " <예제> [App.config] <?xml version="1.0" encoding="utf-8"?> <configuration>   <startup>     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1...