블로그 이미지
따시쿵

calendar

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

Notice

2015. 1. 9. 07:51 C# with TCP/IP

프로그램 설명


msdn 에 있는 예제를 가지고 만든 버전입니다.


TcpListener 클래스 

http://msdn.microsoft.com/ko-kr/library/system.net.sockets.tcplistener(v=vs.110).aspx


TcpClient 클래스

http://msdn.microsoft.com/ko-kr/library/system.net.sockets.tcpclient(v=vs.110).aspx


클라이언트 버전은 사용자 입력을 반복적으로 입력받을 수 있게 수정했습니다.


클라이언트의 메시지를 서버가 받아서 대문자로 변경해 주는 작업만 처리합니다.


실행 후



메시지 전송 후




프로그램 작성 순서


1. 소켓/쓰레드과 관련한 네임스페이스를 서버/클라이언트 모두에 포함 시킵니다.

using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;


2. 서버 프로그램


        static void Main(string[] args)
        {
            TcpListener server = null;

            try
            {
                // Set the TcpListener on port 13000
                Int32 port = 14000;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Starting listening for client requests.
                server.Start();

                // Buffer for reading data
                byte[] bytes = new byte[256];
                string data = string.Empty;

                // Enter the listening loop
                while(true)
                {
                    Console.WriteLine("Waiting for a connection...");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    data = string.Empty;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int bytesRead = 0;
                    // Loop to receive all the data sent by the client
                    while( (bytesRead=stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a UTF8.
                        data = Encoding.UTF8.GetString(bytes, 0, bytesRead);
                        Console.WriteLine("Received: {0}", data);

                        // Process tha data sent by the client
                        data = data.ToUpper();

                        byte[] msg = Encoding.UTF8.GetBytes(data);

                        // Send back a response
                        stream.Write(msg, 0, msg.Length);
                        Console.WriteLine("Sent: {0}\n", data);
                    }

                    // Shutdown and end connection
                    client.Close();
                }
            }
            catch(SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.Message.ToString());
            }
            finally
            {
                // Stop listening for new clients
                server.Stop();
            }

            Console.WriteLine("\nHit enter to continue...");
            Console.Read(); 
        }

3. 클라이언트 프로그램


        static void Main(string[] args)
        {
            string sendData = string.Empty;
            do
            {
                Console.Write("\n전송할 데이타를 입력해 주세요 : ");
                sendData = Console.ReadLine();

                if (!string.IsNullOrEmpty(sendData))
                    Connect("127.0.0.1", sendData);
            } while (sendData != "");
            
            Console.WriteLine("\nPress Enter to continue...");
            Console.Read();
        }

        static void Connect(string server, string message)
        {
            try
            {
                // Create a TcpClient
                // Note, for this client to work you need to have a TcpServer
                // connected to the same address as specified by the server, port
                // combination
                Int32 port = 14000;
                TcpClient client = new TcpClient(server, port);

                // Get a client stream for reading and writing
                // Stream stream = client.GetStream() : System.IO needs..
                NetworkStream stream = client.GetStream();

                // Translate the passed message into UTF8 and store it as Byte array.
                byte[] data = Encoding.UTF8.GetBytes(message);

                // Send the message to the connected TcpServer
                stream.Write(data, 0, data.Length);

                Console.WriteLine("Sent: {0}", message);

                // Receive the TcpServer response

                // Buffer to store the response bytes.
                data = new byte[256];

                // string to store the response ASCII representation.
                string responseData = string.Empty;

                Int32 bytesRead = stream.Read(data, 0, data.Length);
                responseData = Encoding.UTF8.GetString(data, 0, bytesRead);
                Console.WriteLine("Received: {0}", responseData);

                // Close everything
                stream.Close();
                client.Close();
            }
            catch(ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e.Message.ToString());
            }
            catch(SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e.Message.ToString());
            }
        }



posted by 따시쿵