1. 程式人生 > 其它 >C#串列埠通訊例項

C#串列埠通訊例項

本文參考《C#網路通訊程式設計》(張曉明 編著)

程式介面如下圖:

引數設定介面程式碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace ComDemo
{
    public partial class ComSet : Form
    {
        public ComSet()
        {
            InitializeComponent();
        }

        private void ComSet_Load(object sender, EventArgs e)
        {
            //串列埠
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                cmbPort.Items.Add(port);
            }
            cmbPort.SelectedIndex = 0;

            //波特率
            cmbBaudRate.Items.Add("110");
            cmbBaudRate.Items.Add("300");
            cmbBaudRate.Items.Add("1200");
            cmbBaudRate.Items.Add("2400");
            cmbBaudRate.Items.Add("4800");
            cmbBaudRate.Items.Add("9600");
            cmbBaudRate.Items.Add("19200");
            cmbBaudRate.Items.Add("38400");
            cmbBaudRate.Items.Add("57600");
            cmbBaudRate.Items.Add("115200");
            cmbBaudRate.Items.Add("230400");
            cmbBaudRate.Items.Add("460800");
            cmbBaudRate.Items.Add("921600");
            cmbBaudRate.SelectedIndex = 5;

            //資料位
            cmbDataBits.Items.Add("5");
            cmbDataBits.Items.Add("6");
            cmbDataBits.Items.Add("7");
            cmbDataBits.Items.Add("8");
            cmbDataBits.SelectedIndex = 3;

            //停止位
            cmbStopBit.Items.Add("1");
            cmbStopBit.SelectedIndex = 0;

            //佼驗位
            cmbParity.Items.Add("");
            cmbParity.SelectedIndex = 0;
        }

        private void bntOK_Click(object sender, EventArgs e)
        {
            //以下4個引數都是從窗體MainForm傳入的
            MainForm.strProtName = cmbPort.Text;
            MainForm.strBaudRate = cmbBaudRate.Text;
            MainForm.strDataBits = cmbDataBits.Text;
            MainForm.strStopBits = cmbStopBit.Text;
            DialogResult = DialogResult.OK;
        }

        private void bntCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}


主介面程式碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Threading;

namespace ComDemo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private Thread getRecevice;
        protected Boolean stop = false;
        protected Boolean conState = false;
        private StreamReader sRead;
        string strRecieve;
        bool bAccpet = false;

        SerialPort sp = new SerialPort();//例項化串列埠通訊類
        //以下定義4個公有變數,用於引數傳遞
        public static string strProtName = "";
        public static string strBaudRate = "";
        public static string strDataBits = "";
        public static string strStopBits = "";

        private void MainForm_Load(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            groupBox2.Enabled = false;
            this.toolStripStatusLabel1.Text = "埠號:埠未開啟 | ";
            this.toolStripStatusLabel2.Text = "波特率:埠未開啟 | ";
            this.toolStripStatusLabel3.Text = "資料位:埠未開啟 | ";
            this.toolStripStatusLabel4.Text = "停止位:埠未開啟 | ";
            this.toolStripStatusLabel5.Text = "";
        }
        //串列埠設計
        private void btnSetSP_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            sp.Close();
            ComSet dlg = new ComSet();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                sp.PortName = strProtName;//串列埠號
                sp.BaudRate = int.Parse(strBaudRate);//波特率
                sp.DataBits = int.Parse(strDataBits);//資料位
                sp.StopBits = (StopBits)int.Parse(strStopBits);//停止位
                sp.ReadTimeout = 500;//讀取資料的超時時間,引發ReadExisting異常
            }
        }
        //開啟/關閉串列埠
        private void bntSwitchSP_Click(object sender, EventArgs e)
        {
            if (bntSwitchSP.Text == "開啟串列埠")
            {
                if (strProtName != "" && strBaudRate != "" && strDataBits != "" && strStopBits != "")
                {
                    try
                    {
                        if (sp.IsOpen)
                        {
                            sp.Close();
                            sp.Open();//開啟串列埠
                        }
                        else
                        {
                            sp.Open();//開啟串列埠
                        }
                        bntSwitchSP.Text = "關閉串列埠";
                        groupBox1.Enabled = true;
                        groupBox2.Enabled = true;
                        this.toolStripStatusLabel1.Text = "埠號:" + sp.PortName + " | ";
                        this.toolStripStatusLabel2.Text = "波特率:" + sp.BaudRate + " | ";
                        this.toolStripStatusLabel3.Text = "資料位:" + sp.DataBits + " | ";
                        this.toolStripStatusLabel4.Text = "停止位:" + sp.StopBits + " | ";
                        this.toolStripStatusLabel5.Text = "";

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("錯誤:" + ex.Message, "C#串列埠通訊");
                    }
                }
                else
                {
                    MessageBox.Show("請先設定串列埠!", "RS232串列埠通訊");
                }
            }
            else
            {
                timer1.Enabled = false;
                timer2.Enabled = false;
                bntSwitchSP.Text = "開啟串列埠";
                if (sp.IsOpen)
                    sp.Close();
                groupBox1.Enabled = false;
                groupBox2.Enabled = false;
                this.toolStripStatusLabel1.Text = "埠號:埠未開啟 | ";
                this.toolStripStatusLabel2.Text = "波特率:埠未開啟 | ";
                this.toolStripStatusLabel3.Text = "資料位:埠未開啟 | ";
                this.toolStripStatusLabel4.Text = "停止位:埠未開啟 | ";
                this.toolStripStatusLabel5.Text = "";
            }
        }
        //傳送資料
        private void bntSendData_Click(object sender, EventArgs e)
        {
            if (sp.IsOpen)
            {
                try
                {
                    sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");
                    sp.Write(txtSend.Text);//傳送資料
                }
                catch (Exception ex)
                {
                    MessageBox.Show("錯誤:" + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("請先開啟串列埠!");
            }
        }
        //選擇檔案
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.InitialDirectory = "c\\";
            open.RestoreDirectory = true;
            open.FilterIndex = 1;
            open.Filter = "txt檔案(*.txt)|*.txt";
            if (open.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (open.OpenFile() != null)
                    {
                        txtFileName.Text = open.FileName;
                    }
                }
                catch (Exception err1)
                {
                    MessageBox.Show("檔案開啟錯誤!  " + err1.Message, "提示資訊", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        //傳送檔案內容
        private void bntSendFile_Click(object sender, EventArgs e)
        {
            string fileName = txtFileName.Text.Trim();
            if (fileName == "")
            {
                MessageBox.Show("請選擇要傳送的檔案!", "Error");
                return;
            }
            else
            {
                //sRead = new StreamReader(fileName);
                sRead = new StreamReader(fileName,Encoding.Default);//解決中文亂碼問題
            }
            timer1.Start();
        }
        //傳送檔案時鐘
        private void timer1_Tick(object sender, EventArgs e)
        {
            string str1;
            str1 = sRead.ReadLine();
            if (str1 == null)
            {
                timer1.Stop();
                sRead.Close();
                MessageBox.Show("檔案傳送成功!", "C#串列埠通訊");
                this.toolStripStatusLabel5.Text = "";
                return;
            }
            byte[] data = Encoding.Default.GetBytes(str1);
            sp.Write(data, 0, data.Length);
            this.toolStripStatusLabel5.Text = "   檔案傳送中...";
        }
        //接收資料
        private void btnReceiveData_Click(object sender, EventArgs e)
        {
            if (btnReceiveData.Text == "接收資料")
            {
                sp.Encoding = Encoding.GetEncoding("GB2312");
                if (sp.IsOpen)
                {
                    //timer2.Enabled = true; //使用主執行緒進行

                    //使用委託以及多執行緒進行
                    bAccpet = true;
                    getRecevice = new Thread(new ThreadStart(testDelegate));
                    //getRecevice.IsBackground = true;
                    getRecevice.Start();
                    btnReceiveData.Text = "停止接收";
                }
                else
                {
                    MessageBox.Show("請先開啟串列埠");
                }
            }
            else
            {
                //timer2.Enabled = false;
                bAccpet = false;
                try
                {   //停止主監聽執行緒
                    if (null != getRecevice)
                    {
                        if (getRecevice.IsAlive)
                        {
                            if (!getRecevice.Join(100))
                            {
                                //關閉執行緒
                                getRecevice.Abort();
                            }
                        }
                        getRecevice = null;
                    }
                }
                catch { }
                btnReceiveData.Text = "接收資料";
            }
        }
        private void testDelegate()
        {
            reaction r = new reaction(fun);
            r();
        }
        //用於接收資料的定時時鐘
        private void timer2_Tick(object sender, EventArgs e)
        {
            string str = sp.ReadExisting();
            string str2 = str.Replace("\r", "\r\n");
            txtReceiveData.AppendText(str2);
            txtReceiveData.ScrollToCaret();
        }
        //下面用到了接收資訊的代理功能,此為設計的要點之一
        delegate void DelegateAcceptData();
        void fun()
        {
            while (bAccpet)
            {
                AcceptData();
            }
        }

        delegate void reaction();
        void AcceptData()
        {
            if (txtReceiveData.InvokeRequired)
            {
                try
                {
                    DelegateAcceptData ddd = new DelegateAcceptData(AcceptData);
                    this.Invoke(ddd, new object[] { });
                }
                catch { }
            }
            else
            {
                try
                {
                    strRecieve = sp.ReadExisting();
                    txtReceiveData.AppendText(strRecieve);
                }
                catch (Exception ex) { }
            }
        }

        private 
void bntClear_Click(object sender, EventArgs e) { txtReceiveData.Text = ""; } private void button3_Click(object sender, EventArgs e) { try { string path = Directory.GetCurrentDirectory() + @"\output.txt";
string content = this.txtReceiveData.Text; FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter write = new StreamWriter(fs); write.Write(content); write.Flush(); write.Close(); fs.Close(); MessageBox.Show("接收資訊匯出在:" + path); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
JAVA&NET技術QQ群號:456257217有問題的可以在群裡面提問。