communication method

Serial communication:

using CommunicationInterfaceForm.Script;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CommunicationInterfaceForm
{
    public partial class MainForm : Form
    {
        public SerialPort com = new SerialPort();
        //定义端口类
        private SerialPort ComDevice = new SerialPort();
        private SqlConnDB sqlcline = new SqlConnDB();
        public MainForm()
        {
            InitializeComponent();
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            //初始化数据
            comboBox2.Text = "9600";
            comboBox5.Text = "0";
            comboBox3.Text = "8";
            comboBox4.Text = "1";
            InitralConfig(int.Parse(comboBox2.Text));
        }
        /// <summary>
        /// 从注册表获取系统串口列表
        /// </summary>
        public string[] GetComList()
        {
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            string[] sSubKeys = keyCom.GetValueNames();
            string[] str = new string[sSubKeys.Length];
            for (int i = 0; i < sSubKeys.Length; i++)
            {
                str[i] = (string)keyCom.GetValue(sSubKeys[i]);
            }
            return str;
        }
        /// <summary>
        /// 配置初始化
        /// </summary>
        private void InitralConfig(int btl)
        {
            Boolean open = false;
            string[] coms = GetComList();
            for (int i = 0; i < coms.Length; i++)
            {
                open = false;
                if (com.IsOpen)
                {
                    com.Close();
                }
                comboBox1.Items.Add(coms[i]);
            }
            if (comboBox1.Items.Count >= 0) {
                comboBox1.SelectedIndex = 0;
            }
            // to ComDevice.DataReceived (an event) a register method Com_DataReceived, when the port information is always received class will automatically call Com_DataReceived method
            ComDevice.DataReceived + = new new SerialDataReceivedEventHandler (Com_DataReceived);
        }
        /// <Summary>
        /// ComDevice.DataReceived incident upon it from the received serial display data to the reception terminal box
        /// </ Summary>
        /// <param name = "SENDER"> </ param>
        /// <param name = "SENDER"> </ param>
        /// <param name = "SENDER"> </ param>
        /// <param name = "E"> </ param>
        Private void Com_DataReceived (Object SENDER, SerialDataReceivedEventArgs E)
        {
            // open the receive buffer
            byte [] = ReDatas new new byte [ComDevice.BytesToRead];
            // read the data from the serial port
            ComDevice.Read (ReDatas, 0, ReDatas.Length) ;
            // realize data decoding and display
            AddData (ReDatas);
        }
        /// <Summary>
        /// decoding process
        /// </ summary>
        data encoding /// <param name = "data" > serial communications port varies due to, need, to obtain the serial information </ param >
        public void AddData (byte [] Data)
        {
            the StringBuilder the StringBuilder new new SB = ();
            for (int I = 0; I <data.length; I ++)
            {
                sb.AppendFormat ( "{0: X2}" + "", Data [I]);
            }
            addContent (sb.ToString ()); // the ToUpper ().
        }
        /// <Summary>
        /// receiving terminal displays the message box
        /// </ Summary>
        /// <param name = "Content"> </ param>
        Private void addContent (String Content)
        {
            BeginInvoke (new new MethodInvoker ( the delegate
            {
                textBox1.AppendText (Content);
            }));
            // save data to a database
            IF (string.IsNullOrWhiteSpace (Content))!
            {
                String SQL = string.Format ( "INSERT iNTO Test (the Content, Equipment's) values ( ' {0} ',' pretending device ') ", Content);
                int = A sqlcline.update (SQL);
                if (a == -1)
                {
                    MessageBox.Show ( "Database connection error");
                }
            }
        }
        /// <Summary>
        /// serial switch
        /// </ Summary>
        /// <param name = "SENDER"> </ param>
        /// <param name = "E"> </ param>
        Private void the button1_Click (SENDER Object, EventArgs E)
        {
            IF (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show ( "No available serial port, check the hardware");
                return;
            }
           
            IF (== ComDevice.IsOpen to false)
            {
                // set the serial port related attributes
                ComDevice.PortName = ComboBox1.Text;
                ComDevice.BaudRate = Convert.ToInt32 (comboBox2.Text);
                ComDevice.Parity = (Parity)Convert.ToInt32(comboBox5.Text);
                ComDevice.DataBits = Convert.ToInt32(comboBox3.Text);
                ComDevice.StopBits = (StopBits)Convert.ToInt32(comboBox4.Text);
                try
                {
                    //开启串口
                    ComDevice.Open();
                    button2.Enabled = true;
                    button1.Text = "关闭";
                    //接收数据
                    ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
                }
                catch (Exception ex)
                {
                    MessageBox.Show (ex.Message, "failed open port", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            the else
            {
                the try
                {
                    ComDevice.Close ();
                    button2.Enabled = to false;
                }
                the catch (Exception EX )
                {
                    MessageBox.Show (ex.Message, "serial off error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Button1.Text = "ON";
            }
            comboBox1.Enabled = !ComDevice.IsOpen;
            comboBox2.Enabled = !ComDevice.IsOpen;
            comboBox3.Enabled = !ComDevice.IsOpen;
            comboBox4.Enabled = !ComDevice.IsOpen;
            comboBox5.Enabled = !ComDevice.IsOpen;
        }
        /// <summary>
        /// 将消息编码并发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            byte[] sendData = null;
            sendData = Hex16StringToHex16Byte(textBox1.Text);
            SendData(sendData);
        }
        /// <Summary>
        /// This method is used to convert a string of 16 hexadecimal to hexadecimal byte array
        /// </ Summary>
        /// <param name = "_ hex16ToString"> to convert hexadecimal string. </ param>
        public static byte [] Hex16StringToHex16Byte (String _hex16String)
        {
            // remove the spaces in the string.
            = _hex16String.Replace _hex16String ( "", "");
            IF (_hex16String.Length / 2 == 0)
            {
                _hex16String + = "";
            }
            // declare a byte array whose length is equal to half the length of the string.
            byte [] = new new byte Buffer [_hex16String.Length / 2];
            for (int I = 0; I <buffer.Length; I ++)
            {
                // assigned to elements of an array of bytes.
                Buffer [I] = Convert.ToByte ((_ hex16String.Substring (I * 2, 2)), 16);
            }
            // return a byte array.
            Buffer return;
        }
        /// <Summary>
        /// This function encoded message is transmitted to the serial
        /// </ Summary>
        /// <param name = "Data"> </ param>
        /// <Returns> </ Returns >
        public BOOL the SendData (byte [] Data)
        {
            IF (ComDevice.IsOpen)
            {
                the try
                {
                    // the message to the serial port
                    ComDevice.Write (Data, 0, data.length);
                    return to true;
                }
                the catch (Exception EX)
                {
                    MessageBox.Show (ex.Message, "transmission failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            The else
            {
                MessageBox.Show ( "Serial not open", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return to false;
        }
        /// <summary>
        /// 16进制编码
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0) hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
            return returnBytes;
        }
      
    }
}
 socket communication
using httpClient.script;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Management;
namespace httpClient
{
    enum AgreeType
    {
        UDP,
        TCP
    }
    public partial class Form1 : Form
    {
        private static SqlConnDB sqlcline = new SqlConnDB();
        TCPClient tc = new TCPClient();
        private static byte[] result = new byte[1024];
        static Socket serverSocket;
        Thread myThread;
        //udp的socket
        private static Socket udpServer;
        //tcp的socket
        private static Socket clientSocket;
        public Form1()
        {
            InitializeComponent();
            comboBox1.SelectedIndex = 0;
            comboBox3.Items.Add(GetAddressIP());
            comboBox3.SelectedIndex = 0;
        }
        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        private string GetAddressIP()
        {
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.Equals(button1.Text, "连接"))
            {
                switch (comboBox1.SelectedIndex)
                {
                    case (int)AgreeType.TCP:
                        //服务器IP地址           
                        IPAddress ip = IPAddress.Parse(GetAddressIP());
                        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        serverSocket.Bind(new IPEndPoint(ip, Convert.ToInt32(textBox2.Text)));
                        //绑定IP地址:端口           
                        serverSocket.Listen (10);
                        // set up a connection request queue 10          
                        textBox1.AppendText (string.Format ( "{0} successful start listening", serverSocket.LocalEndPoint.ToString ()));
                        // send data through Clientsoket           
                        = the Thread new new myThread (ListenClientConnect);
                        myThread.Start ();
                        // ListenClientConnect ();
                        BREAK;
                    Case (int) AgreeType.UDP:
                        //1.Socket creat           
                        UDPServer new new = the Socket (AddressFamily.InterNetwork, SocketType.Dgram, the ProtocolType .Udp);
                        //2.Bind ip and port           
                        udpServer.Bind(new IPEndPoint(IPAddress.Parse(GetAddressIP()),Convert.ToInt32(textBox2.Text)));
                        //3.receive data           
                        new Thread(UdpRecivceMsg) {IsBackground = true}.Start();
                        break;
                    default:
                        break;
                }
                button1.Text = "关闭";
                comboBox1.Enabled = false;
                comboBox3.Enabled = false;
                textBox2.Enabled = false;
            }else
            {
                button1.Text = "连接";
                comboBox1.Enabled = true;
                comboBox3.Enabled = true;
                textBox2.Enabled = true;
                if (string.Equals(comboBox1.Text, "TCP"))
                {
                    close();
                }
                if (string.Equals(comboBox1.Text, "UDP"))
                {
                    udpServer.Close();
                }
            }
        }

        #region udp实例
        private void UdpSendMsg(string msg)
        {
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            EndPoint serverPoint = new IPEndPoint(IPAddress.Parse(GetAddressIP()), 9999);
            byte[] data = Encoding.UTF8.GetBytes(msg);
            udpClient.SendTo(data, serverPoint);
        }
 
        /// <Summary>
        /// received data
        /// </ Summary>
        Private static void UdpRecivceMsg ()
        {
            the while (to true)
            {
                the EndPoint = new new remoteEndPoint the IPEndPoint (IPAddress.Any, 0);
                byte [] = new new byte Data [1024];
                //MessageBox.Show("1111 ");
                int length = udpServer.ReceiveFrom (data, remoteEndPoint REF);
                // save data to a database
               
                //MessageBox.Show("eee");
                // this method the data source ip, port into the second parameter               
                string message = Encoding.UTF8.GetString (data, 0 , length);
                MessageBox.Show("从ip" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "Get" + message);
                if (!string.IsNullOrWhiteSpace(message))
                {
                    string sql = string.Format("insert into test (Content,Equipment) values ('{0}','假装是设备')", message);
                    int a = sqlcline.update(sql);
                    if (a == -1)
                    {
                        MessageBox.Show("连接数据库错误");
                    }
                }
            }
        }
        #endregion
        #region tcp实例
        /// <summary>      
        /// /// 监听客户端连接       
        /// /// </summary>       
        private static void ListenClientConnect()
        {
            while (true)
            {
                clientSocket = serverSocket.Accept();
                clientSocket.Send(Encoding.ASCII.GetBytes("Hello,welcome to my new world!"));
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
            }
        }
        /// <summary>      
        ///  发送消息       
        /// </summary>
        private static void SendMessage(string msg)
        {
            clientSocket.Send(Encoding.ASCII.GetBytes(msg));
        }
        /// <summary>       
        /// /// 接收消息       
        /// /// </summary>       
        /// /// <param name="clientSocket"></param>       
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据                   
                    int receiveNumber = myClientSocket.Receive(result);
                    MessageBox.Show(string.Format("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber)));
                    if (!string.IsNullOrWhiteSpace(Encoding.ASCII.GetString(result, 0, receiveNumber)))
                    {
                        string sql = string.Format("insert into test (Content,Equipment) values ('{0}','假装是设备')", Encoding.ASCII.GetString(result, 0, receiveNumber));
                        int a = sqlcline.update(sql);
                        if (a == -1)
                        {
                            MessageBox.Show("连接数据库错误");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }
       

        public void close()
        {
            serverSocket.Close();
            myThread.Abort();
        }
        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            if (string.Equals(comboBox1.Text,"TCP")) {
                SendMessage(textBox1.Text);
            }
            else {
                UdpSendMsg(textBox1.Text);
            }
        }
       
    }
}

Guess you like

Origin www.cnblogs.com/ganzhihui/p/11531510.html