zoukankan      html  css  js  c++  java
  • Socket通信 和 串口通信 (有人的硬件)

     硬件采用的是“有人公司”的串口转wifi模块。该模块可以实现串口透传。

     软件如下

    硬件模块设置为 TCP Server  

    using System;
    using System.Windows.Forms;
    using System.IO.Ports;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Text;
    
    namespace Socket串口
    {
        public partial class FrmMain : Form
        {
            public FrmMain()
            {
                InitializeComponent();
            }
            /// <summary>
            /// 打开软件加载项目
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void FrmMain_Load(object sender, EventArgs e)
            {
                SerialPort();//加载系统当前可用的串口
                Control.CheckForIllegalCrossThreadCalls = false;
            }
            #region 串口部分
    
            #region 定义变量
    
            SerialPort sp = new SerialPort();
            bool isOpen = false;//打开串口标志位
    
            #endregion
            /// <summary>
            /// 加载当前系统当中可用的串口
            /// </summary>
            void SerialPort()
            {
                string[] ports = System.IO.Ports.SerialPort.GetPortNames();
                if (ports == null)
                {
                    MessageBox.Show("本机没有串口!");
                }
                foreach (string port in System.IO.Ports.SerialPort.GetPortNames())
                {
                    cbx_Port.Items.Add(port);
                }
                //添加波特率
                cbx_Baude_Rate.Items.Add("1200");
                cbx_Baude_Rate.Items.Add("2400");
                cbx_Baude_Rate.Items.Add("4800");
                cbx_Baude_Rate.Items.Add("9600");
                cbx_Baude_Rate.Items.Add("19200");
                cbx_Baude_Rate.Items.Add("38400");
                cbx_Baude_Rate.Items.Add("43000");
                cbx_Baude_Rate.Items.Add("56000");
                cbx_Baude_Rate.Items.Add("57600");
                cbx_Baude_Rate.Items.Add("115200");
    
                cbx_Baude_Rate.SelectedIndex = 3;
                cbx_Port.SelectedIndex = 0;
    
            }
    
            #region 打开和关闭串口资源
    
            private void SetPortProperty()
            {
    
                sp.PortName = cbx_Port.Text.Trim();
                sp.BaudRate = Convert.ToInt32(cbx_Baude_Rate.Text.Trim());
                sp.StopBits = StopBits.One;
                sp.DataBits = Convert.ToInt16(8);
                sp.Parity = Parity.None;
                sp.ReadTimeout = -1;//超读时间
                sp.RtsEnable = true;
                //定义一个串口接受数据 触发事件
                sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
            }
            void openSerialPort()
            {
                try
                {
                    sp.Open();
                }
                catch
                {
                    MessageBox.Show("打开失败!");
                }
    
            }
            void closeSerialPort()
            {
                try
                {
                    sp.Close();
                }
                catch
                {
                    MessageBox.Show("关闭失败!");
                }
    
            }
    
            private void btn_Open_Port_Click(object sender, EventArgs e)
            {
                if (isOpen == false)
                {
                    SetPortProperty();
                    openSerialPort();
                    isOpen = true;
    
                }
            }
    
            /// <summary>
            /// 串口接收字符事件
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                string ReadStr = "";
                ReadStr = sp.ReadExisting();
                Show_Port_Msg(socketSend.RemoteEndPoint + ":" + ReadStr);
            }
            void Show_Port_Msg(string str)
            { 
                if(txt_Port_Recv.TextLength>300)
                {
                    txt_Port_Recv.Clear();
                }
                txt_Port_Recv.AppendText(str + "
    ");
            }
    
    
            private void btn_Close_Port_Click(object sender, EventArgs e)
            {
                if (isOpen == true)
                {
                    closeSerialPort();
                    isOpen = true;
                    sp.Dispose();
                }
            }
    
            #endregion
            /// <summary>
            /// 在串口接收窗口显示当前接收到的数据
            /// </summary>
            /// <param name="a">接收到的具体数据</param>
            public void ShowTxt(string a)
            {
                this.txt_Port_Recv.AppendText(DateTime.Now.ToString() + " | " + a + "
    ");
                if (txt_Port_Recv.TextLength > 300)
                {
                    txt_Port_Recv.Clear();
                }
            }
    
            #region 发送窗口是否有数据 bool类型  CheckSendData()
            private bool CheckSendData()//检查发送数据窗口是否有数据
            {
                if (txt_Port_Send.Text.Trim() == "") return false;
                return true;
            }
    
            private void btn_Com_Port_Send_Click(object sender, EventArgs e)
            {
                try
                {
                    if (isOpen)
                    {
                        string str = txt_Port_Send.Text.Trim();
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
                        sp.WriteLine(str);
                    }
                    else
                    {
                        MessageBox.Show("请打开串口!");
                    }
                }
    
                catch { }
            }
            #endregion
    
            #region  发送串口数据  btn_Send_Click事件
    
            private void btnSend_Click(object sender, EventArgs e)//发送串口数据
            {
                if (isOpen)//写串口数据
                {
                    if (!CheckSendData())//检测要发送的数据
                    {
                        MessageBox.Show("请输入要发送的数据!", "错误提示");
                        return;
                    }
                    else
                    {
                        try
                        {
                            sp.WriteLine(txt_Port_Send.Text.Trim());
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("发送数据时发生错误!", "错误提示");
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("串口未打开!", "错误提示");
                    return;
                }
            }
    
            #endregion
            
            #endregion
    
    
            #region socket部分
    
            #region Socket相关的定义变量
            Socket socketSend;
            #endregion
    
            /// <summary>
            /// Socket发送数据
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btn_Send_Click(object sender, EventArgs e)
            {
                string str = txt_Socket_Send.Text.Trim();
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
                socketSend.Send(buffer);
            }
            /// <summary>
            /// 建立Socket连接
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btn_Start_Click(object sender, EventArgs e)
            {
                try
                {
                    socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPAddress ip = IPAddress.Parse(txt_IP.Text);
                    IPEndPoint point=new IPEndPoint(ip,Convert.ToInt32(txt_Port.Text.Trim()));
                    socketSend.Connect(point);
                    ShowMsg("连接成功!");
                    Thread th=new Thread(Recive);
                    th.IsBackground=true;
                    th.Start();
                }
                catch { }
            }
            void ShowMsg(string str)
            {            
                if (txt_Socket_Reccv.TextLength>300)
                {
                    txt_Socket_Reccv.Clear();
                }
                txt_Socket_Reccv.AppendText(str + "
    ");
            }
            /// <summary>
            /// 不停的接受服务器发来的消息
            /// </summary>
            void Recive()
            {
                while (true)
                {
                    try
                    {
                        byte[] buffer = new byte[1024 * 1024 * 3];
                        int r = socketSend.Receive(buffer);
                        //实际接收到的有效字节数
                        if (r == 0)
                        {
                            break;
                        }
                        string s = Encoding.UTF8.GetString(buffer, 0, r);
                        ShowMsg(socketSend.RemoteEndPoint + ":" + s);                  
                    }
                    catch { }
                }
            }
            #endregion
            
        }
    }

    最后实现了

  • 相关阅读:
    maven打包不执行测试用例
    maven不打包子模块资源文件
    mvn打包时添加version和profile
    eclipse控制台中文乱码解决方法
    eclipse常用插件
    Spring Boot系列之-logging
    Spring Boot系列之-profile
    Spring Boot系列之-helloword入门
    sqlite入门
    解决eclipse spring配置报错:cvc-elt.1: Cannot find the declaration of element
  • 原文地址:https://www.cnblogs.com/xc2444/p/5581973.html
Copyright © 2011-2022 走看看