블로그 이미지
따시쿵

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

Notice

2015. 1. 15. 16:29 C# with TCP/IP

프로그램 설명


서버와 클라이언트를 각각 쓰레드를 이용한 멀티프로그램으로 예제를 만들어 보았습니다.


실행 후



메시지 전송 후



프로그램 작성 순서


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

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

2. 서버 프로그램

        private void btnStart_Click(object sender, EventArgs e)
        {
            Thread tcpServerRunThread = new Thread(new ThreadStart(TcpServerRun));
            tcpServerRunThread.IsBackground = true;
            tcpServerRunThread.Start();
        }

        private void TcpServerRun()
        {
            TcpListener tcpListener = new TcpListener(IPAddress.Any, 5004);
            tcpListener.Start();
            updateUI("Listening");
            updateUI("===========================================");

            while(true)
            {
                TcpClient client = tcpListener.AcceptTcpClient();
                updateUI("Connected");
                Thread tcpHandlerThread = new Thread(new ParameterizedThreadStart(tcpHandler));
                tcpHandlerThread.Start(client);
            }
        }

        private void tcpHandler(object client)
        {
            TcpClient mClient = client as TcpClient;
            NetworkStream stream = mClient.GetStream();
            byte[] message = new byte[1024];
            int byteRead = stream.Read(message, 0, message.Length);
            updateUI("New Message = " + Encoding.UTF8.GetString(message, 0, byteRead));
            updateUI("");

            stream.Close();
            mClient.Close();
        }

        private void updateUI(string s)
        {
            Action del = delegate()
            {
                textBox1.AppendText(s + System.Environment.NewLine);
            };
            Invoke(del);
        }

3. 클라이언트 프로그램

        private void btnSend_Click(object sender, EventArgs e)
        {
            Thread mThread = new Thread(new ThreadStart(SendAsClient));
            mThread.Start();
        }

        private void SendAsClient()
        {
            TcpClient client = new TcpClient();
            client.Connect(IPAddress.Parse(textServerIP.Text), Convert.ToInt32(textServerPort.Text));
            updateUI("Connected");

            NetworkStream stream = client.GetStream();

            string sendData = textMessage.Text;
            byte[] msg = new byte[256];
            msg = Encoding.UTF8.GetBytes(sendData);

            stream.Write(msg, 0, msg.Length);
            updateUI(string.Format("send data : {0}", sendData));
            updateUI(string.Format("{0} bytes sent", msg.Length ));

            stream.Close();
            client.Close();
        }

        private void updateUI(string s)
        {
            Func<int> del = delegate()
            {
                textBox1.AppendText(s + System.Environment.NewLine);
                return 0;
            };
            Invoke(del);
        }


posted by 따시쿵
2015. 1. 13. 16:16 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. 서버 프로그램

        TcpListener server = null;
 
        public MainForm()
        {
            InitializeComponent();
            FormClosing += new FormClosingEventHandler(Form_Closing);
        }

        private void Form_Closing(object sender, FormClosingEventArgs e)
        {
            if (server != null)
                server = null;

            Application.Exit();
        }
        
        private void btnListen_Click(object sender, EventArgs e)
        {
            new Thread(delegate()
                {
                    try
                    {
                        // Set the TcpListener on port 14000.
                        Int32 port = 14000;
                        IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                        // TcpListener server = new TcpListener(port);
                        server = new TcpListener(localAddr, port);
                        server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

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

                        // Buffer for reading data
                        Byte[] bytes = new Byte[256];
                        String data = null;
                        
                        // Enter the listening loop.
                        while (true)
                        {
                            Invoke((MethodInvoker)delegate
                            {
                                listBox1.Items.Add("Waiting for a connection... ");
                            });

                            // Perform a blocking call to accept requests.
                            // You could also user server.AcceptSocket() here.
                            TcpClient client = server.AcceptTcpClient();
                            Invoke((MethodInvoker)delegate
                            {
                                listBox1.Items.Add("Connected!");
                            });

                            data = null;

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

                            int i;

                            // Loop to receive all the data sent by the client.
                            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                // Translate data bytes to a ASCII string.
                                data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
                                Invoke((MethodInvoker)delegate
                                {
                                    listBox1.Items.Add(string.Format("Received: {0}", data));
                                });

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

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

                                // Send back a response.
                                stream.Write(msg, 0, msg.Length);
                                Invoke((MethodInvoker)delegate
                                {
                                    listBox1.Items.Add(string.Format("Sent: {0}", data));
                                    listBox1.Items.Add("");
                                });
                            }

                            // Shutdown and end connection
                            client.Close();
                        }  // end of outer while                    
                    }
                    catch (SocketException se)
                    {
                        MessageBox.Show(string.Format("SocketException: {0}", se.Message.ToString()));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(string.Format("Exception: {0}", ex.Message.ToString()));
                    }
                    finally
                    {
                        // Stop listening for new clients.
                        server.Stop();
                    }
            }).Start();
        }

2. 클라이언트 프로그램


        private void btnSend_Click(object sender, EventArgs e)
        {
            string serverIP = textServerIP.Text;
            string sendData = textMessage.Text;

            SendMessage(serverIP, sendData);
        }

        private void SendMessage(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);

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

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

                NetworkStream stream = client.GetStream();

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

                Invoke((MethodInvoker)delegate
                {
                    listBox1.Items.Add(string.Format("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;

                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.UTF8.GetString(data, 0, bytes);
                Invoke((MethodInvoker)delegate
                {
                    listBox1.Items.Add(string.Format("Received: {0}", responseData));
                    listBox1.Items.Add("");
                });

                // Close everything.
                stream.Close();
                client.Close();
            }
            catch (ArgumentNullException e)
            {
                MessageBox.Show(string.Format("ArgumentNullException: {0}", e.Message.ToString()));
            }
            catch (SocketException e)
            {
                MessageBox.Show(string.Format("SocketException: {0}", e.Message.ToString()));
            }
        }
posted by 따시쿵
prev 1 next