最近出现硬件单片机与软件连接不稳定的清空,原来使用的TCP连接是为了防止丢包,但是并没有完全杜绝丢包,所以就直接使用UDP连接了,速度快还不用检测连接与否,单片机发就行了。UDP连接呢无所谓服务端跟客户端,他们每个都是单独的主机,只要知道对放的ip就可以发送消息,所以服务端跟客户端代码基本相同只是发送或者接收消息处理的地方不一样。
[code]csharpcode:

using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace CPR
{
    class Program
    {   //主机ip
        public static string serverIP;
        public static string glasssIP;//眼镜IP(由于眼镜的性能不高所以需要把单片机的数据处理啊好以后再发送给眼镜,所以这里记录眼镜IP以便发送)                           
        public static int serverPort = 6000;
        //服务器
        public static Socket socketServer;
       
        public static Thread td;
        
        public static int distance = 0;//按压距离
        public static int gasflow = 0;//气流量
       

        static void Main(string[] args)
        {
            Init();

            Console.ReadLine();

        }

        /// <summary>
        /// 初始化
        /// </summary>
        static void Init(){
            WriteIP();
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socketServer.Bind(new IPEndPoint(IPAddress.Parse(serverIP), 6000));//绑定端口号和IP
            Console.WriteLine("服务端已经开启");
            td = new Thread(ReceiveData);
            td.Start();
        }
        /// <summary>
        /// 向指定ip的主机发送数据
        /// </summary>
        static void SendMsg(string msg,string clientIP)
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse(clientIP), 6000);
            socketServer.SendTo(Encoding.UTF8.GetBytes(msg), point);
        }

        /// <summary>
        /// 接收发送给本机ip对应端口号的数据
        /// </summary>
        static void ReceiveData()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                byte[] buffer = new byte[1024];
                int length = socketServer.ReceiveFrom(buffer, ref point);//接收数据报
                string message = Encoding.UTF8.GetString(buffer, 0, length);
                Console.WriteLine(message);
                if (message== "I am a glasses")//眼镜开启Socket的时候发送身份信息
                {
                    string[] s = point.ToString().Split(':');
                    glasssIP = s[0];//眼镜IP记录
                }
                else
                {
                    ExtractData(message);
                }
            }
        }
        public static void WriteIP()
        {
            if (File.Exists("IP.Config"))
            {
                StreamReader file = new StreamReader("IP.Config", Encoding.UTF8);
                serverIP = file.ReadLine().Trim();
                file.Close();
            }
            else
            {
                System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
                for (int i = 0; i < addressList.Length; i++)
                {
                    if (addressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        serverIP = addressList[i].ToString();
                        break;
                    }
                }
            }
        }
        //上次距离
        public static int lateDistance = 0;
        /// <summary>
        /// 数据解析处理
        /// </summary>
        static void ExtractData(string s)
        {
            //Console.WriteLine("原数据:"+s);
            try
            {
                s = s.Substring(s.IndexOf("{"));
                s = s.Substring(0, s.IndexOf("}") + 1);
                //content.text += "提取:"+s;
                if (s.Contains("slm"))
                {
                    try
                    {
                        Slm slm = JsonConvert.DeserializeObject<Slm>(s);
                        if (slm.slm > 100)
                        {
                            Console.WriteLine("气流量:" + slm.slm);
                            if (!string.IsNullOrEmpty(glasssIP))
                            {
                                SendMsg(slm.slm.ToString() + "+吹气量",glasssIP);
                            }
                            //Send(slm.slm.ToString() + "+吹气量");
                        }
                    }
                    catch (Exception)
                    {
                        //content.text += "转换失败";
                        throw;
                    }

                }
                else if (s.Contains("distance"))
                {
                    try
                    {
                        Dis dis = JsonConvert.DeserializeObject<Dis>(s);
                       
                        if (Math.Abs(dis.distance - lateDistance) > 20)
                        {
                            //Console.WriteLine("距离:" + dis.distance);
                            if (dis.distance != 0)
                            {
                                Console.WriteLine("这次距离:" + dis.distance + "上次距离:" + lateDistance);
                                lateDistance = dis.distance;
                                SendMsg(dis.distance.ToString() + "+按压距离",glasssIP);
                                //Console.WriteLine("发送的距离:" + dis.distance);
                               
                            }
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("转换失败"); 
                        throw;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("解析失败(可能是别的主机发送的消息):" + e.ToString()); 
            }
        }
       
    }
}
public struct Dis
{
    public int state;
    public int distance;
}
public struct Slm
{
    public int slm;
    public int afm300_in;
}

  

posted on 2021-10-09 19:04  陌洛  阅读(10)  评论(0编辑  收藏  举报