Windows_/Windows_C# & App

C# Socket Multi-thread echo server/client 예제

sosal 2014. 10. 8. 05:28
반응형

/*

 http://sosal.kr/
 * made by so_Sal
 */


기본적인 echo 서버 client / server 프로그램과 거의 동일합니다.

참조: http://sosal.tistory.com/760


하지만, 위 소스의 단점은 2개 이상의 클라이언트가 한번에 echo 서버에 접근하지 못합니다.

Listen 이후에 하나의 client의 메시지만을 기다리고 있기 떄문이죠.


thread를 이용하면 여러 client의 접속을 허락하여 메시지를 받을 수 있습니다.



Client 소스



 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

 

using System.IO;

using System.Net;

using System.Net.Sockets;

 

namespace ConsoleTest

{

    class Program

    {

        static void Main(string[] args)

        {

            int PORT = 5555;

            string IP = "localhost";

 

            NetworkStream NS = null;

            StreamReader SR = null;

            StreamWriter SW = null;

            TcpClient client = null;

 

            try

            {

                client = new TcpClient(IP, PORT); //client 연결

                Console.WriteLine("{0}:{1} 접속하였습니다.", IP, PORT);

                NS = client.GetStream(); // 소켓에서 메시지를 가져오는 스트림

                SR = new StreamReader(NS, Encoding.UTF8); // Get message

                SW = new StreamWriter(NS, Encoding.UTF8); // Send message

 

                string SendMessage = string.Empty;

                string GetMessage = string.Empty;

 

                while ((SendMessage = Console.ReadLine()) != null)

                {

                    SW.WriteLine(SendMessage); // 메시지 보내기

                    SW.Flush();

 

                    GetMessage = SR.ReadLine();

                    Console.WriteLine(GetMessage);

                }

            }

 

            catch (Exception e)

            {

                System.Console.WriteLine(e.Message);

            }

            finally

            {

                if (SW != null) SW.Close();

                if (SR != null) SR.Close();

                if (client != null) client.Close();

 

 

            }

        }

    }

}

 





Server 소스




using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

 

using System.IO;

using System.Net;

using System.Net.Sockets;

using System.Threading;

 

namespace Sock_console_server

{

    class Receiver

    {

        NetworkStream NS = null;

        StreamReader SR = null;

        StreamWriter SW = null;

        TcpClient client;

        public void startClient(TcpClient clientSocket)

        {

            client = clientSocket;

            Thread echo_thread = new Thread(echo);

            echo_thread.Start();

        }

 

        public void echo()

        {

            NS = client.GetStream(); // 소켓에서 메시지를 가져오는 스트림

            SR = new StreamReader(NS, Encoding.UTF8); // Get message

            SW = new StreamWriter(NS, Encoding.UTF8); // Send message

 

            string GetMessage = string.Empty;

            try

            {

                while (client.Connected == true) //클라이언트 메시지받기

                {

                    GetMessage = SR.ReadLine();

 

                    SW.WriteLine("Server: {0} [{1}]", GetMessage, DateTime.Now); // 메시지 보내기

                    SW.Flush();

                    Console.WriteLine("Log: {0} [{1}]", GetMessage, DateTime.Now);

                }

            }

            catch (Exception ee)

            {

 

            }

            finally

            {

 

                SW.Close();

                SR.Close();

                client.Close();

                NS.Close();

            }

        }

    }


    class Program

    {

        static void Main(string[] args)

        {

            TcpListener Listener = null;

            TcpClient client = null;

 

            int PORT = 5555;

           

            Console.WriteLine("서버소켓");

            try

            {

                Listener = new TcpListener(PORT);

                Listener.Start(); // Listener 동작 시작

               

                while (true)

                {

                    client = Listener.AcceptTcpClient();

                    Receiver r = new Receiver();

                    r.startClient(client);

                   

                }

            }

            catch (Exception e)

            {

                System.Console.WriteLine(e.Message);

            }

            finally

            {

            }

        }

    }

}