日期:2014-05-18  浏览次数:21090 次

c#带协议的串口编程
我已经实现了最简单的串口间的通信,但是老师要我在此基础上再加上协议进行通信,能收发固定格式,解析数据信息。当时学网络的时候就有点迷糊,现在不知道怎么下手,看到好多例子都是C++的,没有C#的,希望高手能给我一个简单的C#例子看看,谢谢了~~

------解决方案--------------------
给你看个解析AT指令的sample,
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMSLibrary;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace SMSImpl {
    public class SMSModem {
        public bool IsOpen { get { return isOpen; } }
        public SMSModem(string portName) {
            this.portName = portName;

            Regex r1 = new Regex(@"^\+CMTI\:");
            Regex r2 = new Regex(@"^\+CMGR\:");
            Regex r3 = new Regex(@"^\+RING\:");

            ATBeginHandlerMap.Add(r1, OnBeginCMTI);
            ATBeginHandlerMap.Add(r2, OnBeginCMGR);
            ATBeginHandlerMap.Add(r3, OnBeginRING);

            ATHandlerMap.Add(r1, OnCMTI);
            ATHandlerMap.Add(r2, OnCMGR);
            ATHandlerMap.Add(r3, OnRING);

            responseMap.Add(typeof(SendSMSRequest), OnCMGSResponse);
        }

        public void Open() {
            port = new SerialPort(portName);
            port.Encoding = Encoding.Default;
            port.ReadTimeout = 30000;
            port.WriteTimeout = 30000;
            port.BaudRate = 9600;
            port.RtsEnable = true;

            port.Open();
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            AddRequestToQueue(new SettingReuqest("AT").Execute(port));
            Thread.Sleep(50);
            AddRequestToQueue(new SettingReuqest("ATE0").Execute(port));
            AddRequestToQueue(new SettingReuqest("AT+CMGF=1").Execute(port));
            AddRequestToQueue(new SettingReuqest("AT+CNMI=2,1").Execute(port));
            AddRequestToQueue(new SettingReuqest("AT+CSMP=49,167,0,8").Execute(port));

            isOpen = true;
        }

        public void Close() {
            port.DataReceived -= port_DataReceived;
            port.Close();
            isOpen = false;
        }

        public void Send(SMS arg) {
            if (arg.Text.Length > 70) {
                throw new Exception("短信超过70个字符!");
            }

            AddRequestToQueue(new SendSMSRequest(arg).Execute(port));
        }

        // ----------------------------------
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) {
            string line = string.Empty;

            try {
                while (port.BytesToRead > 0) {
                    line = port.ReadLine();
                    if (!string.IsNullOrEmpty(line) && "\r" != line) {
                        Console.WriteLine(line);
                        receiveBuffer.Add(line);

                        if (!isInterrupt) {
                            if (IsBeginInterrupt(line)) {
                                if (IsEndInterrupt()) {
                                    EndInterrupt();
                                }
                            } else {
                                string c = line.TrimEnd('\r');
                                if ("OK" == c || "ERROR" == c) {
                                    var response = new ModemResponse(receiveBuffer);
                                    response.Request = requestQueue.Dequeue();
                                    Type t = response.Request.GetType();
                                    if (responseMap.ContainsKey(t)) {
                                        responseMap[t](response);
                                    }
                                    receiveBuffer.Clear();
                                }
                            }
                        } else {
                            if (IsEndInt