我的socket服务端客户端通信

服务端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SocketManager;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace HostSocket
{
    public partial class Form1 : Form
    {
        private Host myHost;

        System.Timers.Timer QuotaTimer;//给客户机发送信息
        System.Timers.Timer lidarTimer;//避障器有关
        public System.Timers.Timer CapacityTimer;//计算机容量
        public Form1()
        {
            InitializeComponent();

            //先用这个类把这两个的通信做好
            myHost = new Host();
            //myHost.RegisterClientNumChangedCallback();

            //myHost.RegisterClientNumChangedCallback(clientOnOff);  //客户机上线下线
            //myHost.RegisterDiscoveryCallback(receiveDiscovery);//收到广播消息
            //myHost.RegisterCommandCallback(receiveCommand);//接收到命令消息
            //myHost.OnClientHeartbitTimeout += clientDisconnect;//客户机心跳超时


            //启动服务器
            string name = Dns.GetHostName();
            IPAddress[] ipdrlist = Dns.GetHostAddresses(name);
            IPAddress myIp = ipdrlist.Where(x => x.AddressFamily == AddressFamily.InterNetwork).ToArray()[0];


            int aaa = myHost.Start(myIp, 9995, 9996, 9997, 9998, 9999, 3000);

            //开启服务器

            if (myHost.Start(myIp, 9990, 9996, 9997, 9998, 9999, 3000) != 0)
            {
                //MessageBox.Show("启动服务器失败!");
            }
            else
            {
                //MessageBox.Show("启动服务器成功!");
            }

        }
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello 这是服务端!");
        }

        //收到广播消息
        private void receiveDiscovery(IPEndPoint ip, byte[] message)
        {
            string str = Encoding.UTF8.GetString(message);
            // receiveBox.Dispatcher.Invoke(new Action(() => { receiveBox.AppendText("\n收到广播:" + str); }));
            string str1 = "收到广播";
            byte[] bts = Encoding.UTF8.GetBytes(str1);
            //以广播方式回响,过不了路由
            // myHost.ResponseDiscovery(ip.Port, bts);
            //以单播方式回响
            myHost.ResponseDiscovery(ip.Address, ip.Port, bts);//我到底要如何?我是有潜力的吗?
        }

        //收到命令消息
        private void receiveCommand(AsyncUserToken token, byte[] message)
        {
            string str = Encoding.UTF8.GetString(message); //从PAD端接收的数据 //转换成字符串
            string ip = token.IPAddress.ToString();

            string sendstr = "";
            byte[] bts = new byte[1024];

            if (str.Length >= 4)
            {
                switch (str.Substring(0, 4))
                { 
                    case "1001": //读取参数设置
                        //MessageBox.Show("接收到客户端命令1001,读取参数设置");

                        sendstr = "1001," + "0," + "从服务器,返回的,值#"; 
                        break;
                }
            }

            bts = Encoding.UTF8.GetBytes(sendstr);   //采集/校验指令之后的返回值

            myHost.ResponseCommand(token, bts); //自动向客户端发送信息

        }

        //发送状态 cb_status()接收
        private object locker = new object();
        public void SendStatus(string str)
        {
            lock (locker)
            {
                byte[] bts = Encoding.UTF8.GetBytes(str);
                myHost.SendStatus(bts);
            }
        }

        private void button2_Click(object sender, EventArgs e)//发status
        {
            SendStatus("8003,计算指标错误#");
        }

        private void button3_Click(object sender, EventArgs e)//发data
        {
            QuotaTimer = new System.Timers.Timer();
            QuotaTimer.Elapsed += new System.Timers.ElapsedEventHandler(SendQuota);
            QuotaTimer.Interval = 1000;
            QuotaTimer.Enabled = true;
            QuotaTimer.Start();
             
        }
        //发送Data cb_Data接收
        private int QuoTimer = 0;
        /// <summary>
        /// 往客户机发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendQuota(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref QuoTimer, 1) == 0)
            {
                //发送指标数据
                //string str = PublicModule.Milleage + "," + PublicModule.crossLevalValue + "," + PublicModule.gaugeValue + "," + PublicModule.FourLine + "," +
                //    PublicModule.HorStage_left + "," + PublicModule.VerStage_left + "," + PublicModule.LeftReaHeight + "," + PublicModule.Gap_Left + "," +
                //    PublicModule.HorStage_Right + "," + PublicModule.VerStage_Right + "," + PublicModule.RightReaHeight + "," + PublicModule.Gap_Right + "," +
                //    PublicModule.PinKey_Left + "," + PublicModule.PinKey_Right + "#";
                string str = "里程数据,水平数据,错台数据,轨缝数据#";
                byte[] bts = Encoding.UTF8.GetBytes(str);
                myHost.SendData(bts);

                Interlocked.Exchange(ref QuoTimer, 0);
            }
        }

        #region 客户机上线下线
        //客户机上线下线
        int chNum = 0;
        private void clientOnOff(int ch, string ip, int action)
        {
            if (action == 1)//上线
            {
                chNum++;
                CapacityTimer = new System.Timers.Timer(1000);
                CapacityTimer.Elapsed += new System.Timers.ElapsedEventHandler(CapacityTimer_Tick);
                CapacityTimer.Enabled = true;//设置是否执行Elapsed事件
            }
            else//下线
            {
                chNum = 0;
                if (chNum == 0)
                {
                    if (CapacityTimer != null)
                    {
                        CapacityTimer.Stop();
                        CapacityTimer.Close();
                    }

                    if (true) //小车断开连接后状态
                    {
                        //关闭避障器

                        //关闭摄像头
                    }
                }
            }
        }
        #endregion 客户机上线下线

        #region 磁盘计算有关
        public long storageGB;
        public long freeStorageGB;

        //获取计算机容量的定时器
        private int inTimer = 0;//置一个标志,表示一个Timer处理正在执行,下一个Timer发生的时候发现上一个没有执行完就放弃
        private void CapacityTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)//定时器发送
        {
            //读硬盘总容量和剩余容量
            long storageB = GetHardDiskSpace("C");
            storageGB = ByteConversionGB(storageB);

            if (Interlocked.Exchange(ref inTimer, 1) == 0)
            {


                long freeStorageB = GetHardDiskFreeSpace("C");
                long freeStorageGB = ByteConversionGB(freeStorageB);

                int percent = (int)(Convert.ToDouble(freeStorageGB) / storageGB * 100);

                SendStatus("8001," + percent + "#");//发送计算机容量

                Interlocked.Exchange(ref inTimer, 0);
            }

        }
        /// <summary>
        /// 获取指定驱动器的剩余空间总大小(单位为B)
        /// </summary>
        /// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 </param>
        /// <returns> </returns>
        public static long GetHardDiskFreeSpace(string str_HardDiskName)
        {
            long freeSpace = new long();
            str_HardDiskName = str_HardDiskName + ":\\";
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
            foreach (System.IO.DriveInfo drive in drives)
            {
                if (drive.Name == str_HardDiskName)
                {
                    freeSpace = drive.TotalFreeSpace;
                }
            }
            return freeSpace;

        }


        const int GB = 1024 * 1024 * 1024;//定义GB的计算常量
        const int MB = 1024 * 1024;//定义MB的计算常量
        const int KB = 1024;//定义KB的计算常量
        public Int64 ByteConversionGB(Int64 KSize)
        {
            // if (KSize / GB >= 1)//如果当前Byte的值大于等于1GB
            return ((int)(KSize / (float)GB));//将其转换成GB
            // return (Math.Round(KSize / (float)GB, 0)).ToString() + "GB";//将其转换成GB
            /*   
             *   else if (KSize / MB >= 1)//如果当前Byte的值大于等于1MB
                    return ((int)(KSize / (float)MB));//将其转换成MB
                                                      //return (Math.Round(KSize / (float)MB, 0)).ToString() + "MB";//将其转换成MB
                else if (KSize / KB >= 1)//如果当前Byte的值大于等于1KB
                    return ((int)(KSize / (float)KB));//将其转换成KGB
                                                      // return (Math.Round(KSize / (float)KB, 0)).ToString() + "KB";//将其转换成KGB
                else
                    return KSize;//显示Byte值
            */
            //return KSize.ToString() + "Byte";//显示Byte值
        }

        /// 获取指定驱动器的空间总大小(单位为B)
        /// </summary>
        /// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 </param>
        /// <returns> </returns>
        public static long GetHardDiskSpace(string str_HardDiskName)
        {
            long totalSize = new long();
            str_HardDiskName = str_HardDiskName + ":\\";
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
            foreach (System.IO.DriveInfo drive in drives)
            {
                if (drive.Name == str_HardDiskName)
                {
                    totalSize = drive.TotalSize;
                }
            }
            return totalSize;
        }

        #endregion 磁盘计算有关

        #region 客户机心跳超时
        private void clientDisconnect(string ip)
        {
            chNum = 0;
            MessageBox.Show(ip + "心跳超时!");
            if (CapacityTimer != null)
            {
                CapacityTimer.Stop();
                CapacityTimer.Close();
            }
            if (true)//断开连接后停车
            {
                //小车停止
                //关闭避障器
                //关闭摄像头
            }
        }

        #endregion 客户机心跳超时
    }
}

客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SocketManager;
using System.Net;

namespace VistorSocket
{
    public partial class Form1 : Form
    {
        public Visitor myVisitor;
        
        IPAddress serverIP = IPAddress.Parse("10.29.95.16");
        public Form1()
        {
            InitializeComponent();

            myVisitor = new Visitor(9995, 9996, 9997, 9998, 9999, 3000);

            //注册回调函数
            myVisitor.RegisterDiscoveryCallback(cb_discovery);//广播消息回调
            myVisitor.RegisterCommandCallback(cb_command);//命令消息返回后的函数   //命令指令
            myVisitor.RegisterDataCallback(cb_data);//数据消息回调函数             //实时返回数据
            myVisitor.RegisterStatusCallback(cb_status);//状态消息返回后的回调函数  //返回状态
            myVisitor.OnDisconnneted += DoDisconnneted;//服务器断开连接

            //myVisitor.Connect(ipserver, 1000);
            //bool conn = myVisitor.Connected;
        }
         
        private void button1_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Hello 这是客户端");
            connect(serverIP);

            byte[] buff=new byte[1024];
            //cb_command(buff);

            //cb_data(buff);
        }

        //IP连接
        public void connect(IPAddress serverIp)
        {
            if (myVisitor != null && !myVisitor.Connected)
            {
                if (0 == myVisitor.Connect(serverIP, 1000))
                {
                    byte[] cmdMessage=new byte[1024];//发送缓冲区
                    cmdMessage = Encoding.UTF8.GetBytes("1001");//读取设置参数
                    int res = myVisitor.SendCommand(cmdMessage);
                }
                MessageBox.Show("连接成功");
            }
            else
            {
                MessageBox.Show("连接失败");
            }
        }

        //广播消息回调
        private void cb_discovery(IPEndPoint iPEndPoint, byte[] buff)
        {
            string str = Encoding.UTF8.GetString(buff);
            string ip = iPEndPoint.Address.ToString();
            // Response.Dispatcher.Invoke(new Action(() => { Response.AppendText("\n广播消息来自:" + ip + str); }));
            //lstFind.Dispatcher.Invoke(new Action(() => { lstFind.Items.Add(ip); }));
        }

        //命令消息返回后的回调函数
        private void cb_command(byte[] buff) //自动收到了从服务器返回的信息
        {
            try
            {
                string str = Encoding.UTF8.GetString(buff);
                if (str.Length >= 4)
                {
                    switch (str.Substring(0, 4))
                    { 
                        case "1001"://读取设置参数
                            string[] returnVal = str.Split(new Char[] { ',', '#' }, StringSplitOptions.RemoveEmptyEntries);

                            if (returnVal[0] == "1001" && returnVal[1] == "0")
                            {
                                //控件接收请求返回数据

                            }

                            MessageBox.Show("从服务器返回的值" + str.ToString());

                            break;
                    }
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        //数据消息回调函数
        private void cb_data(byte[] buff)
        {
            string str = Encoding.UTF8.GetString(buff);
            string[] returnVal = str.Split(new Char[] { ',', '#' });
            //MessageBox.Show("命令请求的返回消息");
            //使用

            //获取到的服务端的实时数据
            string str1 = returnVal[0]; ;
            string str2 = returnVal[2]; ;
            string str3 = returnVal[3]; ;
        }

        int bb = 0;
        //状态消息返回后的回调函数
        private void cb_status(byte[] buff)
        {
            string str = Encoding.UTF8.GetString(buff);
            string[] returnVal = str.Split(new Char[] { ',', '#' }, StringSplitOptions.RemoveEmptyEntries);

            //MessageBox.Show("接收到装态数据" + returnVal[0]);
        }

        //服务器断开连接
        int discCnt = 0;
        DateTime dt = new DateTime();
        private void DoDisconnneted()
        {
            if ((DateTime.Now - dt).TotalMilliseconds > 5000)
            {
                discCnt = 1;
            }
            else
            {
                discCnt += 1;
            }
            dt = DateTime.Now;
            if (discCnt > 2)
            {
                myVisitor.Disconnect();
                MessageBox.Show("服务器长时间未响应,客户机已经断开连接!");
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值