Esempio n. 1
0
        /// <summary>

        /// 接收客户端发来的信息,客户端套接字对象

        /// </summary>

        /// <param name="socketclientpara"></param>

        private void recv(object socketclientpara)

        {
            Socket socketServer = socketclientpara as Socket;



            while (true)

            {
                //创建字节数组接收客户端的数据 返回值length表示接收了多少字节的数据,根据结构体计算出来长度大小

                byte[] arrServerRecMsg = new byte[Marshal.SizeOf(typeof(SocketDateStruct)) + 2];

                //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度

                try

                {
                    int length = socketServer.Receive(arrServerRecMsg);

                    byte[] dataValue = new byte[Marshal.SizeOf(typeof(SocketDateStruct))]; //数据用于crc
                    Array.Copy(arrServerRecMsg, 0, dataValue, 0, length - 2);

                    byte[] myCRC = SoftCRC16.CRC16(dataValue);

                    if (myCRC[myCRC.Length - 1] == arrServerRecMsg[myCRC.Length - 1] && myCRC[myCRC.Length - 2] == arrServerRecMsg[myCRC.Length - 2])   //验证CRC高位和地位是否相等
                    {
                        SocketDateStruct socketDateStruct = new SocketDateStruct();
                        socketDateStruct = MarshalHelper.BytesToStruct <SocketDateStruct>(arrServerRecMsg);

                        string strStruct = socketDateStruct.devId + ";" + socketDateStruct.Temperature.ToString() + ";" + socketDateStruct.Humidity.ToString() +
                                           ";" + socketDateStruct.Distance.ToString() + ";" + socketDateStruct.XAxisAcceleration.ToString() +
                                           ";" + socketDateStruct.YAxisAcceleration.ToString() + ";" + socketDateStruct.ZAxisAcceleration.ToString() +
                                           ";" + socketDateStruct.PitchAngle.ToString() + ";" + socketDateStruct.RollAngle.ToString() + ";" + socketDateStruct.CourseAngle.ToString();

                        writeListBox("接收到了一条消息:结构体数据->" + strStruct);
                    }
                    else
                    {
                        writeListBox("接收到了一条消息:收到的数据CRC错误");
                    }
                    string strData2 = BitConverter.ToString(arrServerRecMsg);  //只把接收到的数据(0 - length)进行转化
                    writeListBox("接收到了一条消息:原始的byte->" + strData2);

                    //将机器接受到的字节数组转换为人可以读懂的字符串

                    //string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
                    string strSRecMsg = "12345";



                    //将发送的字符串信息附加到文本框txtMsg上

                    writeListBox("\r\n[客户端:" + socketServer.RemoteEndPoint + " 时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "]\r\n" + strSRecMsg);



                    //Thread.Sleep(3000);

                    //socketServer.Send(Encoding.UTF8.GetBytes("[" + socketServer.RemoteEndPoint + "]:"+strSRecMsg));

                    //发送客户端数据

                    if (ClientConnectionItems.Count > 0)

                    {
                        foreach (var socketTemp in ClientConnectionItems)

                        {
                            socketTemp.Value.Send(Encoding.UTF8.GetBytes("[" + socketServer.RemoteEndPoint + "]:" + strSRecMsg));
                        }
                    }
                }

                catch (Exception)

                {
                    ClientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString());

                    //提示套接字监听异常

                    writeListBox("\r\n[客户端\"" + socketServer.RemoteEndPoint + "\"已经中断连接! 客户端数量:" + ClientConnectionItems.Count + "]");

                    //关闭之前accept出来的和客户端进行通信的套接字

                    socketServer.Close();

                    break;
                }
            }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="common">发送数据</param>
        /// <param name="data">命令码</param>
        /// <returns></returns>
        public ComResult <RT> Send <T, RT>(int common, T data)
            where T : struct
            where RT : struct
        {
            ComResult <RT> result = new ComResult <RT>();

            try
            {
                //发送命令码
                byte[] commonData = BitConverter.GetBytes(common);
                byte[] sendStruct = MarshalHelper.StructToBytes(data);

                //发送数据
                byte[] sendData = new byte[sendStruct.Length + 11];
                sendData[0] = 0xff;
                sendData[1] = 0x01;
                sendData[2] = 0x00;
                Array.Copy(commonData, 0, sendData, 3, 4);
                sendData[7] = 0x01;
                Array.Copy(BitConverter.GetBytes(sendStruct.Length), 0, sendData, 8, 2);
                Array.Copy(sendStruct, 0, sendData, 10, sendStruct.Length);
                sendData[sendData.Length - 1] = DataCheck(sendData);

                //准备接收缓冲区
                int receiveDataSize = Marshal.SizeOf(typeof(RT));

                //发送数据
                var receiveDate = SendData(sendData, receiveDataSize);

                if (receiveDate[0] == 0xff && receiveDate[2] == 0x01)
                {
                    //校验数据
                    if (receiveDate[receiveDate.Length - 1] != DataCheck(receiveDate))
                    {
                        result.Result = ComResultEnum.VerificationError;
                    }

                    //解析数据
                    int dataLength = BitConverter.ToInt16(receiveDate, 8); //获取数据长度
                    if (dataLength == receiveDataSize)
                    {
                        byte[] dataBytes = new byte[dataLength];
                        Array.Copy(receiveDate, 10, dataBytes, 0, dataLength);
                        result.Data = MarshalHelper.BytesToStruct <RT>(dataBytes);
                    }
                    else
                    {
                        result.Result = ComResultEnum.VerificationError;
                    }
                }
                else
                {
                    result.Result = ComResultEnum.VerificationError;
                }
            }
            catch (Exception ex)
            {
                result.Result = ComResultEnum.TimeOut;
            }

            return(result);
        }