블로그 이미지
따시쿵

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. 3. 10. 10:49 C# with SerialPort

프로그램 설명


인스턴스 메시지 기능으로 통신하는 프로그램입니다.


사용한 시리얼포트는 COM3(write), COM4(read) 이며, 설정 화면은 아래와 같습니다.




실행 후




메시지 전송 후







프로그램 작성


        public Form1()
        {
            InitializeComponent();
        }

        private static string RxString = string.Empty;

        #region initButton click method
        private void initButton_Click(object sender, EventArgs e)
        {
            try
            {
                // 시리얼 포트가 열려 있는지 확인
                if (!serialPortWrite.IsOpen && !serialPortRead.IsOpen)
                {
                    // 메시지 출력
                    richTextBoxCom4.Text = serialPortWrite.PortName + " Ready!!!" + Environment.NewLine;
                    richTextBoxCom4.AppendText(serialPortRead.PortName + " Ready!!!" + Environment.NewLine);

                    // 포트 오픈
                    serialPortRead.Open();
                    serialPortWrite.Open();

                    // 버튼 비활성화
                    initButton.Enabled = false;
                }
                else
                {
                    richTextBoxCom4.Text = "Port isn't opened";
                }
            }
            catch(UnauthorizedAccessException ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
        #endregion

        #region Form1_FormClosing method
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPortWrite.IsOpen)
                serialPortWrite.Close();

            if (serialPortRead.IsOpen)
                serialPortRead.Close();
        }
        #endregion

        #region serialPortRead DataReceived method
        private void serialPortRead_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                RxString = serialPortRead.ReadExisting();
                this.Invoke(new EventHandler(DisplayText));
            }
            catch (TimeoutException ex) { }
        }
        #endregion

        #region Displaytext
        private void DisplayText(object sender, EventArgs e)
        {
            richTextBoxCom4.AppendText(RxString);
        }
        #endregion

        #region sendButton click method
        private void sendButton_Click(object sender, EventArgs e)
        {
            serialPortWrite.Write(richTextBoxCom3.Text + Environment.NewLine);
        }
        #endregion

        #region richTextBoxCom3 KeyPress method
        private void richTextBoxCom3_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(!serialPortWrite.IsOpen || !instanceMS.Checked)
                return;

            char[] buffer = new char[1];
            buffer[0] = e.KeyChar;

            serialPortWrite.Write(buffer, 0, buffer.Length);
        }
        #endregion

        #region clearButton click method
        private void clearButton_Click(object sender, EventArgs e)
        {
            richTextBoxCom3.Text = "";
            richTextBoxCom4.Text = "";
        }
        #endregion

 

 

소스 파일 :

serialPortTest2.zip

 


'C# with SerialPort' 카테고리의 다른 글

[Program C#] 시리얼포트로 읽기/쓰기 - 기본  (0) 2015.03.09
posted by 따시쿵
2015. 3. 9. 17:00 C# with SerialPort

프로그램 설명


일반 컴퓨터에서 개발을 하기 위해서는 몇가지 선행 준비 작업을 해야 합니다.


준비사항 


1. putty 를 인스톨하여 시뮬레이션을 테스트 

   ==> https://bitbucket.org/daybreaker/iputty/downloads


2. 가상 시리얼포트를 만듦 

   ==> Com0Com v3.0.0.0 W7 x64 (64bit) signed



Com0Com 설정 및  PC 장치관리자 셋팅 후의 모습




실행 후




메시지 전송 후


프로그램 작성 순서


1. 디자인 화면




2. 코드 화면


        public Form1()
        {
            InitializeComponent();
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen){
                serialPort1.PortName = "COM4";
                serialPort1.Open();
                richTextBox1.Text = "opened";

                btnInit.Enabled = false;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen)
                serialPort1.Close();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                string text = richTextBox1.Text;
                serialPort1.Write(text + Environment.NewLine);
            }
        }


posted by 따시쿵
2015. 3. 6. 16:46 C# with TCP/IP
프로그램 설명

비동기로 접속을 하고 데이타를 주고 받는 방법중에 method 뒤에 SocketAsyncEventArgs class 를 이용하는 방법입니다.

실행 후



데이타 전송 후




프로그램 작성 순서


1. 서버 프로그램


        #region MainForm
        public MainForm()
        {
            InitializeComponent();
        }
        #endregion

        #region MainForm_Load
        private Socket m_ServerSocket;
        private List m_ClientSocket;
        private byte[] szData;

        private void MainForm_Load(object sender, EventArgs e)
        {
            m_ClientSocket = new List();

            m_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 10000);
            m_ServerSocket.Bind(ipep);
            m_ServerSocket.Listen(20);

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.Completed += new EventHandler(Accept_Completed);
            m_ServerSocket.AcceptAsync(args);
        }
        #endregion

        #region Accept_Completed
        private void Accept_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket ClientSocket = e.AcceptSocket;
            m_ClientSocket.Add(ClientSocket);

            //접속한 클라이언수 보이기
            label1.Text = m_ClientSocket.Count.ToString();

            try
            { 
                if (m_ClientSocket != null)
                {
                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();

                    szData = new byte[1024];
                    args.SetBuffer(szData, 0, szData.Length);
                    args.UserToken = m_ClientSocket;
                    args.Completed += new EventHandler(Receive_Completed);
                    ClientSocket.ReceiveAsync(args);
                }

                e.AcceptSocket = null;
                m_ServerSocket.AcceptAsync(e);
             }
            catch(SocketException se)
            {
                Trace.WriteLine(string.Format("SocketException : {0}", se.Message));
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception : {0}", ex.Message));
            }
        }
        #endregion

        #region Receive_Completed
        private void Receive_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket ClientSocket = sender as Socket;

            if (ClientSocket.Connected && e.BytesTransferred > 0)
            {
                byte[] szData = e.Buffer;
                string sData = Encoding.Unicode.GetString(szData);

                sData = sData.Replace("\0", "").Trim();
                SetText(sData);
                e.SetBuffer(szData, 0, 1024);
                ClientSocket.ReceiveAsync(e);
            }
            else
            {
                ClientSocket.Disconnect(false);
                ClientSocket.Dispose();
                m_ClientSocket.Remove(ClientSocket);
            }

            //접속한 클라이언수 보이기
            label1.Text = m_ClientSocket.Count.ToString();
        }
        #endregion

        #region SetText
        private delegate void SetTextCallback(string text);
        private void SetText(string text)
        {
            if (richTextBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                if (richTextBox1.TextLength > 0)
                {
                    richTextBox1.AppendText("\n");
                }

                richTextBox1.AppendText(text);
                richTextBox1.ScrollToCaret();
            }
        }
        #endregion

        #region Dispose
        protected override void Dispose(bool disposing)
        {
            foreach(Socket pBuffer in m_ClientSocket)
            {
                if (pBuffer.Connected)
                    pBuffer.Disconnect(false);
                pBuffer.Dispose();
            }
            m_ServerSocket.Dispose();

            if (disposing && components != null)
                components.Dispose();

            base.Dispose(disposing);
        }
        #endregion


2. 클라이언트 프로그램


        #region MainForm
        public MainForm()
        {
            InitializeComponent();
        }
        #endregion

        private Socket m_ClientSocket = null;

        #region MainForm_Load
        private void MainForm_Load(object sender, EventArgs e)
        {
            m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteIP = new IPEndPoint(IPAddress.Parse("192.168.0.12"), 10000);

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.RemoteEndPoint = remoteIP;

            m_ClientSocket.ConnectAsync(args);
        }
        #endregion

        #region button1_Click method
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length > 0)
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                byte[] szData = Encoding.Unicode.GetBytes(textBox1.Text);

                args.SetBuffer(szData, 0, szData.Length);
                m_ClientSocket.SendAsync(args);

                textBox1.Text = "";
                textBox1.Focus();
            }
        }
        #endregion

        #region Dispose
        protected override void Dispose(bool disposing)
        {
            if (m_ClientSocket.Connected)
                m_ClientSocket.Disconnect(false);
            m_ClientSocket.Dispose();

            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #endregion

posted by 따시쿵