블로그 이미지
따시쿵

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

Notice

2015. 3. 13. 15:39 Asp.net with WebSocket

프로그램 설명


websocket을 이용해서 메시지를 주고 받는 라이브러리가 있어서 소개합니다.


셋팅하는 방법은 파일을 다운받은 후, mssql db 를 인스톨하고 디비명과 아이디, 비밀번호를 셋팅하고, 다운로드 받은 파일을 웹 서버 폴더 밑에 두거나 localhost 로 운영할 수 있는 곳이면 셋팅은 모두 완료입

니다.


라이브러리 다운 받을 곳 : http://cutesoft.net/asp.net+Chat/



실행 후





posted by 따시쿵
2015. 3. 12. 16:41 C# with TCP/IP

프로그램 설명


한 프로그램에서 여러개의 포트를 열어서 작업이 필요한 경우입니다.

포트별로 쓰레드를 만들어서 작업하는 방식입니다. 예제에서는 8080, 8081 포트를 엽니다.




실행 후



프로그램 작성 순서


1. ListenPorts.cs


    class ListenPorts
    {
        Socket[] socket;
        IPEndPoint[] ipEndPoint;

        internal ListenPorts(IPEndPoint[] ipEndPoint)
        {
            this.ipEndPoint = ipEndPoint;
            socket = new Socket[ipEndPoint.Length];
        }

        public void beginListen()
        {
            for(int i = 0; i < ipEndPoint.Length; i++)
            {
                socket[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket[i].Bind(ipEndPoint[i]);

                Thread t_handler = new Thread(threadListen);
                t_handler.IsBackground = true;
                t_handler.Start(socket[i]);
            }
        }

        private void threadListen(object sender)
        {
            Socket m_client = sender as Socket;
            byte[] data = new byte[1024];
            
            try
            {
                m_client.Listen(100);
                Socket newSocket = m_client.Accept();
                int bytes = newSocket.Receive(data);

                IPEndPoint remoteIP = newSocket.RemoteEndPoint as IPEndPoint;
                IPEndPoint localIP = newSocket.LocalEndPoint as IPEndPoint;

                Console.WriteLine("server ip : {0} remote ip : {1} ", localIP.ToString(), remoteIP.ToString());
                Console.WriteLine("Received data : {0}", Encoding.Unicode.GetString(data, 0, bytes));
                
                string msg = "Welcome to multiple server";
                byte[] buffer = Encoding.Unicode.GetBytes(msg);
                newSocket.Send(buffer, buffer.Length, SocketFlags.None);
                Console.WriteLine("Send data : {0}", msg);
                Console.WriteLine();
            }
            catch(SocketException se)
            {
                Console.WriteLine(se.Message);
            }
            
        }
    }


2. 서버 프로그램


    class Program
    {
        static void Main(string[] args)
        {
            IPEndPoint ipEndPoint1 = new IPEndPoint(IPAddress.Any, 8080);
            IPEndPoint ipEndPoint2 = new IPEndPoint(IPAddress.Any, 8081);

            IPEndPoint[] ipEndPoint = new IPEndPoint[2] { ipEndPoint1, ipEndPoint2 };
            //IPEndPoint[] ipEndPoint = new IPEndPoint[1] { ipEndPoint1 };

            ListenPorts listenport = new ListenPorts(ipEndPoint);
            listenport.beginListen();
            Console.WriteLine("Begin Listen");
            Console.WriteLine();
            
            Console.ReadKey();
        }
    }


3. 클라이언트 프로그램


    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];

            //TCP Client

            Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());
            Console.WriteLine();

            //Set the IP address of the server, and its port.
            IPEndPoint ipep1 = new IPEndPoint(IPAddress.Parse("192.168.0.12"), 8080);
            IPEndPoint ipep2 = new IPEndPoint(IPAddress.Parse("192.168.0.12"), 8081);
            string welcome = "Hello, Multiple server ! ";

            // port 8080 으로 전송
            try
            {
                // 소켓 생성
                Socket server1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 메시지 전송
                data = Encoding.Unicode.GetBytes(welcome);
                server1.Connect(ipep1);
                server1.Send(data);
                Console.WriteLine("Send by the port : {0}", server1.LocalEndPoint.ToString());
                Console.WriteLine("Send data : {0}", welcome);

                // 메시지 받음
                byte[] msg = new byte[1024];
                int bytes = server1.Receive(msg);
                Console.WriteLine("Received data : {0}", Encoding.Unicode.GetString(msg, 0, bytes));
                Console.WriteLine();
                // 소켓 닫기
                server1.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // port 8081 으로 전송
            try
            {
                // 소켓 생성
                Socket server2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 메시지 전송
                data = Encoding.Unicode.GetBytes(welcome);
                server2.Connect(ipep2);
                server2.Send(data);
                Console.WriteLine("Send by the port : {0}", server2.LocalEndPoint.ToString());
                Console.WriteLine("Send data : {0}", welcome);

                // 메시지 받음
                byte[] msg = new byte[1024];
                int bytes = server2.Receive(msg);
                Console.WriteLine("Received data : {0}", Encoding.Unicode.GetString(msg, 0, bytes));
                Console.WriteLine();
                // 소켓 닫기
                server2.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
    }


posted by 따시쿵
2015. 3. 12. 10:20 C# with TCP/IP

프로그램 설명


TcpListener와 TcpClient를 이용한 1:1 통신을 하는 프로그램입니다.

서버와 클라이언트 통신하는 순서와 아래와 같습니다.




실행 후




메시진 전송 후




프로그램 작성 순서


1. 서버 프로그램


    public partial class MainForm : Form
    {
        TcpListener serverSocket = null;
        TcpClient clientSocket = null;

        public MainForm()
        {
            InitializeComponent();

            // socket start
            new Thread(delegate()
                {
                    InitSocket();
                }).Start();
        }

        private void InitSocket()
        {
            try
            { 
                serverSocket = new TcpListener(IPAddress.Any, 9999);
                clientSocket = default(TcpClient);
                serverSocket.Start();
                DisplayText(" >> Server Started");

                clientSocket = serverSocket.AcceptTcpClient();
                DisplayText(" >> Accept connection from client");

                Thread threadHandler = new Thread(new ParameterizedThreadStart(OnAccepted));
                threadHandler.IsBackground = true;
                threadHandler.Start(clientSocket);
            }
            catch (SocketException se)
            {
                DisplayText(string.Format("InitSocket : SocketException : {0}", se.Message));
            }
            catch (Exception ex)
            {
                DisplayText(string.Format("InitSocket : Exception : {0}", ex.Message));
            }
        }

        private void OnAccepted(object sender)
        {
            TcpClient clientSocket = sender as TcpClient;

            while (true)
            {
                try
                {
                    NetworkStream stream = clientSocket.GetStream();
                    byte[] buffer = new byte[1024];

                    stream.Read(buffer, 0, buffer.Length);
                    string msg = Encoding.Unicode.GetString(buffer);
                    msg = msg.Substring(0, msg.IndexOf("$"));
                    DisplayText(" >> Data from client - " + msg);

                    string response = "Last Message from client - " + msg;
                    byte[] sbuffer = Encoding.Unicode.GetBytes(response);

                    stream.Write(sbuffer, 0, sbuffer.Length);
                    stream.Flush();

                    DisplayText(" >> " + response);
                }
                catch (SocketException se)
                {
                    DisplayText(string.Format("OnAccepted : SocketException : {0}", se.Message));
                    break;
                }
                catch (Exception ex)
                {
                    DisplayText(string.Format("OnAccepted : Exception : {0}", ex.Message));
                    break;
                }
            }

            clientSocket.Close();
        }

        private void DisplayText(string text)
        {
            if (richTextBoxMsg.InvokeRequired)
            {
                richTextBoxMsg.BeginInvoke(new MethodInvoker(delegate
                {
                    richTextBoxMsg.AppendText(text + Environment.NewLine);
                }));
            }
            else
                richTextBoxMsg.AppendText(text + Environment.NewLine);
 
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (clientSocket != null)
            { 
                clientSocket.Close();
                clientSocket = null;
            }

            if (serverSocket != null)
            {
                serverSocket.Stop();
                serverSocket = null;
            }
        }
    }


2. 클라이언트 프로그램


    public partial class MainForm : Form
    {
        TcpClient clientSocket = new TcpClient();

        public MainForm()
        {
            InitializeComponent();

            new Thread(delegate()
            {
                InitSocket();
            }).Start();      
        }

        private void InitSocket()
        {
            try
            { 
                clientSocket.Connect("192.168.0.12", 9999);
                DisplayText("Client Started");
                labelStatus.Text = "Client Socket Program - Server Connected ...";
            }
            catch (SocketException se) 
            {
                MessageBox.Show(se.Message, "Error");
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
        
        private void btnSend_Click(object sender, EventArgs e)
        {
            NetworkStream stream = clientSocket.GetStream();
            byte[] sbuffer = Encoding.Unicode.GetBytes(richTextBox2.Text + "$");
            stream.Write(sbuffer, 0, sbuffer.Length);
            stream.Flush();

            byte[] rbuffer = new byte[1024];
            stream.Read(rbuffer, 0, rbuffer.Length);
            string msg = Encoding.Unicode.GetString(rbuffer);
            DisplayText(msg);

            richTextBox2.Text = "";
            richTextBox2.Focus();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (clientSocket != null)
                clientSocket.Close();
        }

        private void DisplayText(string text)
        {
            if (richTextBox1.InvokeRequired)
            {
                richTextBox1.BeginInvoke(new MethodInvoker(delegate
                {
                    richTextBox1.AppendText(Environment.NewLine + " >> " + text);
                }));
            }
            else
                richTextBox1.AppendText(Environment.NewLine + " >> " + text);
        }
    }


posted by 따시쿵