Exemple #1
0
        /// <summary>
        /// 维护超时连接的线程方法
        /// </summary>
        private void ThreadDealWithTimeout()
        {
            LogNet?.WriteInfo("waitting one second");
            Thread.Sleep(1000);// 刚启动的时候进行休眠一小会
            LogNet?.WriteInfo("begining recyle for reading plc");
            while (true)
            {
                DateTime firstTime = DateTime.Now; // 连接时间

                TimerCallBack();                   // 启动访问PLC

                while ((DateTime.Now - firstTime).TotalMilliseconds < Timeout)
                {
                    // 超时时间等待
                }
                // 连接超时处理
                for (int i = 0; i < PlcStates.Length; i++)
                {
                    if (!PlcStates[i].IsConnect)
                    {
                        PlcStates[i].WorkSocket.Close();
                    }
                }

                while ((DateTime.Now - firstTime).TotalMilliseconds < ReadCycle)
                {
                    // 等待下次连接
                }
            }
        }
 private void MqttServer_OnClientApplicationMessageReceive(MqttSession session, MqttClientApplicationMessage message)
 {
     if (session.Protocol == "MQTT")
     {
         // 异步的推送
     }
     else
     {
         // 同步网络
         if (message.Topic == "StartPLC")
         {
             string tmp = StartPLC( );
             LogNet?.WriteInfo(tmp);
             // 远程启动设备
             mqttServer.PublishTopicPayload(session, tmp, Encoding.UTF8.GetBytes(tmp));
         }
         else if (message.Topic == "StopPLC")
         {
             string tmp = StopPLC( );
             LogNet?.WriteInfo(tmp);
             // 远程停止设备
             mqttServer.PublishTopicPayload(session, tmp, Encoding.UTF8.GetBytes(tmp));
         }
         else
         {
             mqttServer.PublishTopicPayload(session, message.Topic, message.Payload);
         }
     }
 }
 /// <summary>
 /// 关闭服务器的引擎
 /// </summary>
 public virtual void ServerClose( )
 {
     if (IsStarted)
     {
         CloseAction( );
         CoreSocket?.Close( );
         IsStarted = false;
         LogNet?.WriteInfo(ToString(), StringResources.Language.NetEngineClose);
     }
 }
        /// <summary>
        /// 根据指定的端口启动Upd侦听
        /// </summary>
        /// <param name="port">端口号信息</param>
        public override void ServerStart(int port)
        {
            if (!IsStarted)
            {
                CoreSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                //绑定网络地址
                CoreSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                RefreshReceive( );
                LogNet?.WriteInfo(ToString(), StringResources.Language.NetEngineStart);
                IsStarted = true;
            }
        }
Exemple #5
0
        private void ContentReceiveCallBack(IAsyncResult ar)
        {
            if (ar.AsyncState is DeviceState stateone)
            {
                try
                {
                    int count = stateone.WorkSocket.EndReceive(ar);

                    if (count > 0)
                    {
                        MemoryStream ms   = new MemoryStream( );
                        byte         next = stateone.Buffer[0];

                        while (next != endByte)
                        {
                            ms.WriteByte(next);
                            byte[] buffer = new byte[1];
                            stateone.WorkSocket.Receive(buffer, 0, 1, SocketFlags.None);
                            next = buffer[0];
                        }

                        // 接收完成
                        stateone.WorkSocket.BeginReceive(stateone.Buffer, 0, stateone.Buffer.Length, SocketFlags.None,
                                                         new AsyncCallback(ContentReceiveCallBack), stateone);


                        byte[] receive = ms.ToArray( );
                        ms.Dispose( );

                        lock_list.Enter( );
                        stateone.ReceiveTime = DateTime.Now;
                        lock_list.Leave( );
                        AcceptBytes?.Invoke(stateone, receive);
                        AcceptString?.Invoke(stateone, Encoding.ASCII.GetString(receive));
                    }
                    else
                    {
                        RemoveClient(stateone);
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.NetClientOffline);
                    }
                }
                catch (Exception ex)
                {
                    //登录前已经出错
                    RemoveClient(stateone);
                    LogNet?.WriteException(ToString( ), StringResources.Language.NetClientLoginFailed, ex);
                }
            }
        }
        private void TcpStateUpLine(AppSession state)
        {
            HybirdLockSockets.Enter( );
            All_sockets_connect.Add(state);
            HybirdLockSockets.Leave( );

            // 提示上线
            ClientOnline?.Invoke(state);
            // 是否保存上线信息
            if (IsSaveLogClientLineChange)
            {
                LogNet?.WriteInfo(ToString(), "IP:" + state.IpAddress + " Name:" + state?.LoginAlias + " " + StringResources.NetClientOnline);
            }
            // 计算客户端在线情况
            AsyncCoordinator.StartOperaterInfomation( );
        }
Exemple #7
0
        /// <summary>
        /// 删除已经存在的文件信息
        /// </summary>
        /// <param name="path">文件的路径</param>
        /// <param name="fileName">文件的名称</param>
        private void DeleteExsistingFile(string path, string fileName)
        {
            if (!string.IsNullOrEmpty(fileName))
            {
                string     fileUltimatePath = path + "\\" + fileName;
                FileMarkId fileMarkId       = GetFileMarksFromDictionaryWithFileName(fileName);

                fileMarkId.AddOperation(() =>
                {
                    if (!DeleteFileByName(fileUltimatePath))
                    {
                        LogNet?.WriteInfo(ToString(), StringResources.Language.FileDeleteFailed + fileUltimatePath);
                    }
                });
            }
        }
        /// <summary>
        /// 启动服务器的引擎
        /// </summary>
        /// <param name="port">指定一个端口号</param>
        public virtual void ServerStart(int port)
        {
            if (!IsStarted)
            {
                StartInitialization( );

                CoreSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                CoreSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                CoreSocket.Listen(500);  //单次允许最后请求500个,足够小型系统应用了
                CoreSocket.BeginAccept(new AsyncCallback(AsyncAcceptCallback), CoreSocket);
                IsStarted = true;

                LogNet?.WriteNewLine( );
                LogNet?.WriteInfo(ToString(), StringResources.NetEngineStart);
            }
        }
Exemple #9
0
        private void TcpStateUpLine(AppSession state)
        {
            lockSessions.Enter( );
            appSessions.Add(state);
            lockSessions.Leave( );

            // 提示上线
            ClientOnline?.Invoke(state);

            AllClientsStatusChange?.Invoke(ClientCount);
            // 是否保存上线信息
            if (IsSaveLogClientLineChange)
            {
                LogNet?.WriteInfo(ToString( ), $"[{state.IpEndPoint}] Name:{ state?.LoginAlias } { StringResources.NetClientOnline }");
            }
        }
Exemple #10
0
        private void TcpStateDownLine(AppSession state, bool is_regular, bool logSave = true)
        {
            lockSessions.Enter( );
            appSessions.Remove(state);
            lockSessions.Leave( );
            // 关闭连接
            TcpStateClose(state);
            // 判断是否正常下线
            string str = is_regular ? StringResources.NetClientOffline : StringResources.NetClientBreak;

            ClientOffline?.Invoke(state, str);
            AllClientsStatusChange?.Invoke(ClientCount);
            // 是否保存上线信息
            if (IsSaveLogClientLineChange && logSave)
            {
                LogNet?.WriteInfo(ToString(), $"[{state.IpEndPoint}] Name:{ state?.LoginAlias } { str }");
            }
        }
        private void TcpStateDownLine(AppSession state, bool is_regular)
        {
            HybirdLockSockets.Enter( );
            All_sockets_connect.Remove(state);
            HybirdLockSockets.Leave( );
            // 关闭连接
            TcpStateClose(state);
            // 判断是否正常下线
            string str = is_regular ? StringResources.NetClientOffline : StringResources.NetClientBreak;

            ClientOffline?.Invoke(state, str);
            // 是否保存上线信息
            if (IsSaveLogClientLineChange)
            {
                LogNet?.WriteInfo(ToString(), "IP:" + state.IpAddress + " Name:" + state?.LoginAlias + " " + str);
            }
            // 计算客户端在线情况
            AsyncCoordinator.StartOperaterInfomation( );
        }
Exemple #12
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            if (ar.AsyncState is AppSession session)
            {
                try
                {
                    Socket client    = session.WorkSocket;
                    int    bytesRead = client.EndReceive(ar);

                    // 正常下线退出
                    LogNet?.WriteInfo(ToString( ), $"客户端 {session.IpEndPoint} 下线");
                    RemoveGroupOnlien(session.KeyGroup, session.ClientUniqueID);
                }
                catch (Exception ex)
                {
                    LogNet?.WriteException(ToString( ), $"客户端 {session.IpEndPoint} 下线", ex);
                    RemoveGroupOnlien(session.KeyGroup, session.ClientUniqueID);
                }
            }
        }
Exemple #13
0
 private void NetSimplify_ReceiveStringEvent(AppSession session, HslCommunication.NetHandle handle, string msg)
 {
     if (handle == 1)
     {
         string tmp = StartPLC( );
         LogNet?.WriteInfo(tmp);
         // 远程启动设备
         netSimplify.SendMessage(session, handle, tmp);
     }
     else if (handle == 2)
     {
         string tmp = StopPLC( );
         LogNet?.WriteInfo(tmp);
         // 远程停止设备
         netSimplify.SendMessage(session, handle, tmp);
     }
     else
     {
         netSimplify.SendMessage(session, handle, msg);
     }
 }
Exemple #14
0
        /// <summary>
        /// 当接收到了新的请求的时候执行的操作
        /// </summary>
        /// <param name="socket">异步对象</param>
        /// <param name="endPoint">终结点</param>
        protected override void ThreadPoolLogin(Socket socket, IPEndPoint endPoint)
        {
            OperateResult result = new OperateResult( );

            // 获取ip地址
            string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( );

            // 接收操作信息
            if (!ReceiveInformationHead(
                    socket,
                    out int customer,
                    out string fileName,
                    out string Factory,
                    out string Group,
                    out string Identify).IsSuccess)
            {
                return;
            }

            string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName);

            if (customer == HslProtocol.ProtocolFileDownload)
            {
                // 先获取文件的真实名称
                string guidName = TransformFactFileName(Factory, Group, Identify, fileName);
                // 获取文件操作锁
                FileMarkId fileMarkId = GetFileMarksFromDictionaryWithFileName(guidName);
                fileMarkId.EnterReadOperator( );
                // 发送文件数据
                OperateResult send = SendFileAndCheckReceive(socket, ReturnAbsoluteFileName(Factory, Group, Identify, guidName), fileName, "", "", null);
                if (!send.IsSuccess)
                {
                    fileMarkId.LeaveReadOperator( );
                    LogNet?.WriteError(ToString( ), $"{StringResources.Language.FileDownloadFailed} : {send.Message} :{relativeName} ip:{IpAddress}");
                    return;
                }
                else
                {
                    LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDownloadSuccess + ":" + relativeName);
                }

                fileMarkId.LeaveReadOperator( );
                // 关闭连接
                socket?.Close( );
            }
            else if (customer == HslProtocol.ProtocolFileUpload)
            {
                string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);
                // 上传文件
                CheckFolderAndCreate( );
                FileInfo info = new FileInfo(fullFileName);

                try
                {
                    if (!Directory.Exists(info.DirectoryName))
                    {
                        Directory.CreateDirectory(info.DirectoryName);
                    }
                }
                catch (Exception ex)
                {
                    LogNet?.WriteException(ToString( ), StringResources.Language.FilePathCreateFailed + fullFileName, ex);
                    socket?.Close( );
                    return;
                }

                // 接收文件并回发消息
                if (ReceiveFileFromSocketAndUpdateGroup(
                        socket,                // 网络套接字
                        fullFileName).IsSuccess)
                {
                    socket?.Close( );
                    LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadSuccess + ":" + relativeName);
                }
                else
                {
                    LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadFailed + ":" + relativeName);
                }
            }
            else if (customer == HslProtocol.ProtocolFileDelete)
            {
                string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                FileInfo           info          = new FileInfo(fullFileName);
                GroupFileContainer fileManagment = GetGroupFromFilePath(info.DirectoryName);

                // 新增删除的任务
                DeleteExsistingFile(info.DirectoryName, fileManagment.DeleteFile(info.Name));

                // 回发消息
                if (SendStringAndCheckReceive(
                        socket,                                                            // 网络套接字
                        1,                                                                 // 没啥含义
                        "success"                                                          // 没啥含意
                        ).IsSuccess)
                {
                    socket?.Close( );
                }

                LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDeleteSuccess + ":" + relativeName);
            }
            else if (customer == HslProtocol.ProtocolFileDirectoryFiles)
            {
                GroupFileContainer fileManagment = GetGroupFromFilePath(ReturnAbsoluteFilePath(Factory, Group, Identify));

                if (SendStringAndCheckReceive(
                        socket,
                        HslProtocol.ProtocolFileDirectoryFiles,
                        fileManagment.JsonArrayContent).IsSuccess)
                {
                    socket?.Close( );
                }
            }
            else if (customer == HslProtocol.ProtocolFileDirectories)
            {
                List <string> folders = new List <string>( );
                foreach (var m in GetDirectories(Factory, Group, Identify))
                {
                    DirectoryInfo directory = new DirectoryInfo(m);
                    folders.Add(directory.Name);
                }

                Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray( ));
                if (SendStringAndCheckReceive(
                        socket,
                        HslProtocol.ProtocolFileDirectoryFiles,
                        jArray.ToString( )).IsSuccess)
                {
                    socket?.Close( );
                }
            }
            else
            {
                // close not supported client
                socket?.Close( );
            }
        }
Exemple #15
0
        /// <summary>
        /// 系统的登录方法
        /// </summary>
        /// <param name="obj"></param>
        protected override void ThreadPoolLogin(object obj)
        {
            Socket socket = obj as Socket;

            try
            {
                //为了兼容原来旧的升级服务,暂时停止令牌功能
                //接收令牌 2017-03-14 10:02:20
                //InfoTcp infoTcp = new InfoTcp()
                //{
                //    Worksocket = socket,
                //};
                //
                //ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckConnect), infoTcp);
                //try
                //{
                //    byte[] token = ReadFromSocket(socket, 16);
                //    infoTcp.IsConnect = true;
                //    if (!IsTwoBytesEquel(KeyToken.ToByteArray(), token))
                //    {
                //        socket.Close();
                //        log_record.SaveNormal("接收到验证失败的连接");
                //        return;
                //    }
                //}
                //catch (Exception ex)
                //{
                //    socket?.Close();
                //    log_record.SaveNormal("令牌接收出错:" + ex.Message);
                //    return;
                //}


                byte[] ReceiveByte = NetSupport.ReadBytesFromSocket(socket, 4);
                int    Protocol    = BitConverter.ToInt32(ReceiveByte, 0);

                if (Protocol == 0x1001 || Protocol == 0x1002)
                {
                    // 安装系统和更新系统
                    if (Protocol == 0x1001)
                    {
                        LogNet?.WriteInfo(StringResources.SystemInstallOperater + ((IPEndPoint)socket.RemoteEndPoint).Address.ToString());
                    }
                    else
                    {
                        LogNet?.WriteInfo(StringResources.SystemUpdateOperater + ((IPEndPoint)socket.RemoteEndPoint).Address.ToString());
                    }
                    if (Directory.Exists(FileUpdatePath))
                    {
                        string[] files = Directory.GetFiles(FileUpdatePath);


                        List <string> Files = new List <string>(files);
                        for (int i = Files.Count - 1; i >= 0; i--)
                        {
                            FileInfo finfo = new FileInfo(Files[i]);
                            if (finfo.Length > 200000000)
                            {
                                Files.RemoveAt(i);
                            }
                            if (Protocol == 0x1002)
                            {
                                if (finfo.Name == "软件自动更新.exe")
                                {
                                    Files.RemoveAt(i);
                                }
                            }
                        }
                        files = Files.ToArray();

                        socket.BeginReceive(new byte[4], 0, 4, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);

                        socket.Send(BitConverter.GetBytes(files.Length));
                        for (int i = 0; i < files.Length; i++)
                        {
                            // 传送数据包含了本次数据大小,文件数据大小,文件名(带后缀)
                            FileInfo finfo    = new FileInfo(files[i]);
                            string   fileName = finfo.Name;
                            byte[]   ByteName = Encoding.Unicode.GetBytes(fileName);

                            int    First     = 4 + 4 + ByteName.Length;
                            byte[] FirstSend = new byte[First];

                            FileStream fs = new FileStream(files[i], FileMode.Open, FileAccess.Read);

                            Array.Copy(BitConverter.GetBytes(First), 0, FirstSend, 0, 4);
                            Array.Copy(BitConverter.GetBytes((int)fs.Length), 0, FirstSend, 4, 4);
                            Array.Copy(ByteName, 0, FirstSend, 8, ByteName.Length);

                            socket.Send(FirstSend);
                            Thread.Sleep(10);

                            byte[] buffer = new byte[4096];
                            int    sended = 0;
                            while (sended < fs.Length)
                            {
                                int count = fs.Read(buffer, 0, 4096);
                                socket.Send(buffer, 0, count, SocketFlags.None);
                                sended += count;
                            }

                            fs.Close();
                            fs.Dispose();

                            Thread.Sleep(20);
                        }
                    }
                }
                else
                {
                    // 兼容原先版本的更新,新的验证方式无需理会
                    socket.Send(BitConverter.GetBytes(10000f));
                    Thread.Sleep(20);
                    socket?.Shutdown(SocketShutdown.Both);
                    socket?.Close();
                }
            }
            catch (Exception ex)
            {
                Thread.Sleep(20);
                socket?.Shutdown(SocketShutdown.Both);
                socket?.Close();
                LogNet?.WriteException(StringResources.FileSendClientFailed, ex);
            }
        }
        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="obj"></param>
        protected override void ThreadPoolLogin(object obj)
        {
            if (obj is Socket socket)
            {
                OperateResult result = new OperateResult();

                // 获取ip地址
                string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString();

                // 接收操作信息
                if (!ReceiveInformationHead(
                        socket,
                        out int customer,
                        out string fileName,
                        out string Factory,
                        out string Group,
                        out string Identify,
                        result,
                        "filename received failed.ip:" + IpAddress
                        ))
                {
                    return;
                }

                string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName);

                // 操作分流

                if (customer == HslCommunicationCode.Hsl_Protocol_File_Download)
                {
                    string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                    // 发送文件数据
                    if (!SendFileAndCheckReceive(socket, fullFileName, fileName, "", "", result, null))
                    {
                        LogNet?.WriteError($"{StringResources.FileDownloadFailed}:{relativeName} ip:{IpAddress}");
                        return;
                    }
                    else
                    {
                        LogNet?.WriteInfo(StringResources.FileDownloadSuccess + ":" + relativeName);
                    }
                    socket?.Close();
                }
                else if (customer == HslCommunicationCode.Hsl_Protocol_File_Upload)
                {
                    string tempFileName = FilesDirectoryPathTemp + "\\" + CreateRandomFileName();

                    string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                    // 上传文件
                    CheckFolderAndCreate();

                    try
                    {
                        FileInfo info = new FileInfo(fullFileName);
                        if (!Directory.Exists(info.DirectoryName))
                        {
                            Directory.CreateDirectory(info.DirectoryName);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogNet?.WriteException("创建文件夹失败:" + fullFileName, ex);
                        socket?.Close();
                        return;
                    }

                    if (ReceiveFileFromSocketAndMoveFile(
                            socket,                             // 网络套接字
                            tempFileName,                       // 临时保存文件路径
                            fullFileName,                       // 最终保存文件路径
                            out string FileName,                // 文件名称,从客户端上传到服务器时,为上传人
                            out long FileSize,
                            out string FileTag,
                            out string FileUpload,
                            result
                            ))
                    {
                        socket?.Close();
                        LogNet?.WriteInfo(StringResources.FileUploadSuccess + ":" + relativeName);
                    }
                    else
                    {
                        LogNet?.WriteInfo(StringResources.FileUploadFailed + ":" + relativeName);
                    }
                }
                else if (customer == HslCommunicationCode.Hsl_Protocol_File_Delete)
                {
                    string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                    bool deleteResult = DeleteFileByName(fullFileName);

                    // 回发消息
                    if (SendStringAndCheckReceive(
                            socket,                                                    // 网络套接字
                            deleteResult ? 1 : 0,                                      // 是否移动成功
                            deleteResult ? "成功" : "失败",                                // 字符串数据
                            result,                                                    // 结果数据对象
                            null,                                                      // 不进行报告
                            "回发删除结果错误")                                                // 发送错误时的数据
                        )
                    {
                        socket?.Close();
                    }

                    if (deleteResult)
                    {
                        LogNet?.WriteInfo(StringResources.FileDeleteSuccess + ":" + fullFileName);
                    }
                }
                else if (customer == HslCommunicationCode.Hsl_Protocol_File_Directory_Files)
                {
                    List <GroupFileItem> fileNames = new List <GroupFileItem>();
                    foreach (var m in GetDirectoryFiles(Factory, Group, Identify))
                    {
                        FileInfo fileInfo = new FileInfo(m);
                        fileNames.Add(new GroupFileItem()
                        {
                            FileName = fileInfo.Name,
                            FileSize = fileInfo.Length,
                        });
                    }

                    Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(fileNames.ToArray());
                    if (SendStringAndCheckReceive(
                            socket,
                            HslCommunicationCode.Hsl_Protocol_File_Directory_Files,
                            jArray.ToString(),
                            result,
                            null,
                            "发送文件列表回客户端失败"))
                    {
                        socket?.Close();
                    }
                }
                else if (customer == HslCommunicationCode.Hsl_Protocol_File_Directories)
                {
                    List <string> folders = new List <string>();
                    foreach (var m in GetDirectories(Factory, Group, Identify))
                    {
                        DirectoryInfo directory = new DirectoryInfo(m);
                        folders.Add(directory.Name);
                    }

                    Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray());
                    if (SendStringAndCheckReceive(
                            socket,
                            HslCommunicationCode.Hsl_Protocol_File_Directory_Files,
                            jArray.ToString(),
                            result,
                            null,
                            "发送文件夹列表回客户端失败"))
                    {
                        socket?.Close();
                    }
                }
                else
                {
                    socket?.Close();
                }
            }
        private void AsyncCallback(IAsyncResult ar)
        {
            if (ar.AsyncState is AppSession session)
            {
                try
                {
                    int received = session.WorkSocket.EndReceiveFrom(ar, ref session.UdpEndPoint);
                    // 马上开始重新接收,提供性能保障
                    RefreshReceive();
                    session.IpEndPoint = (IPEndPoint)session.UdpEndPoint;

                    int    contentLength      = session.BytesContent[2] * 256 + session.BytesContent[3];
                    byte[] dtuNumArray        = new byte[11];
                    byte[] publicNetworkArray = new byte[4];
                    byte[] publicPortArray    = new byte[2];

                    if (contentLength > 0)
                    {
                        Array.Copy(session.BytesContent, 4, dtuNumArray, 0, 11);
                        Array.Copy(session.BytesContent, 15, publicNetworkArray, 0, 4);
                        Array.Copy(session.BytesContent, 19, publicPortArray, 0, 2);
                    }
                    if (session.BytesContent[0] == 0x7b) // 代表宏电DDP协议
                    {
                        string dtuNum = Encoding.ASCII.GetString(dtuNumArray, 0, 11).Trim();
                        // 解析内容
                        if (session.BytesContent[1] == 0x01 && contentLength == 22)                                                // 0x01 终端请求注册
                        {
                            string publicNetwork = BasicFramework.SoftBasic.ByteToHexTenString(publicNetworkArray, '.');           // 终端内网IP
                            int    publicPort    = Convert.ToInt32(BasicFramework.SoftBasic.ByteToHexString(publicPortArray), 16); //终端内网端口
                            SendBytesAsync(session, BuildDtuNumCommand(dtuNumArray));
                            LogNet?.WriteInfo(ToString(), $"请求注册 终端号码:{dtuNum} 终端公网IP:{session.IpEndPoint} 终端内网IP:{publicNetwork}:{publicPort}");
                        }

                        if (session.BytesContent[1] == 0x02 && contentLength == 16) // 0x02 终端请求注销
                        {
                            LogNet?.WriteInfo(ToString(), $"请求注销 终端号码:{dtuNum}");
                        }

                        if (session.BytesContent[1] == 0x09)                           // 0x09 发送给DSC的用户数据包
                        {
                            byte[] instructArray = new byte[session.BytesContent[18]]; // 接收的指令长度(不包含宏电数据头)
                            Array.Copy(session.BytesContent, 16, instructArray, 0, session.BytesContent[18]);

                            LogNet?.WriteInfo(ToString(), $"发送给DSC的用户数据包 终端号码:{dtuNum} 数据捕获:{BasicFramework.SoftBasic.ByteToHexString(instructArray, ' ')}");
                        }
                    }
                    else
                    {
                        LogNet?.WriteWarn(ToString(), $"数据捕获:{BasicFramework.SoftBasic.ByteToHexString(session.BytesContent, ' ')}");
                    }
                }
                catch (ObjectDisposedException)
                {
                    //主程序退出的时候触发
                }
                catch (Exception ex)
                {
                    LogNet?.WriteException(ToString(), StringResources.Language.SocketEndReceiveException, ex);
                    //重新接收,此处已经排除掉了对象释放的异常
                    RefreshReceive();
                }
                finally
                {
                    //state = null;
                }
            }
        }
Exemple #18
0
        /// <summary>
        /// 当接收到了新的请求的时候执行的操作
        /// </summary>
        /// <param name="socket">异步对象</param>
        /// <param name="endPoint">终结点</param>
        protected override void ThreadPoolLogin(Socket socket, IPEndPoint endPoint)
        {
            OperateResult result = new OperateResult( );
            // 获取ip地址
            string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( );

            // 接收操作信息
            OperateResult infoResult = ReceiveInformationHead(
                socket,
                out int customer,
                out string fileName,
                out string Factory,
                out string Group,
                out string Identify);

            if (!infoResult.IsSuccess)
            {
                Console.WriteLine(infoResult.ToMessageShowString( ));
                return;
            }

            string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName);

            // 操作分流

            if (customer == HslProtocol.ProtocolFileDownload)
            {
                string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                // 发送文件数据
                OperateResult sendFile = SendFileAndCheckReceive(socket, fullFileName, fileName, "", "");
                if (!sendFile.IsSuccess)
                {
                    LogNet?.WriteError(ToString( ), $"{StringResources.Language.FileDownloadFailed}:{relativeName} ip:{IpAddress} reason:{sendFile.Message}");
                    return;
                }
                else
                {
                    socket?.Close( );
                    LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDownloadSuccess + ":" + relativeName);
                }
            }
            else if (customer == HslProtocol.ProtocolFileUpload)
            {
                string tempFileName = FilesDirectoryPathTemp + "\\" + CreateRandomFileName( );

                string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                // 上传文件
                CheckFolderAndCreate( );

                // 创建新的文件夹
                try
                {
                    FileInfo info = new FileInfo(fullFileName);
                    if (!Directory.Exists(info.DirectoryName))
                    {
                        Directory.CreateDirectory(info.DirectoryName);
                    }
                }
                catch (Exception ex)
                {
                    LogNet?.WriteException(ToString( ), StringResources.Language.FilePathCreateFailed + fullFileName, ex);
                    socket?.Close( );
                    return;
                }

                OperateResult receiveFile = ReceiveFileFromSocketAndMoveFile(
                    socket,                                 // 网络套接字
                    tempFileName,                           // 临时保存文件路径
                    fullFileName,                           // 最终保存文件路径
                    out string FileName,                    // 文件名称,从客户端上传到服务器时,为上传人
                    out long FileSize,
                    out string FileTag,
                    out string FileUpload
                    );

                if (receiveFile.IsSuccess)
                {
                    socket?.Close( );
                    LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadSuccess + ":" + relativeName);
                }
                else
                {
                    LogNet?.WriteInfo(ToString( ), StringResources.Language.FileUploadFailed + ":" + relativeName + " " + StringResources.Language.TextDescription + receiveFile.Message);
                }
            }
            else if (customer == HslProtocol.ProtocolFileDelete)
            {
                string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);

                bool deleteResult = DeleteFileByName(fullFileName);

                // 回发消息
                if (SendStringAndCheckReceive(
                        socket,                                                            // 网络套接字
                        deleteResult ? 1 : 0,                                              // 是否移动成功
                        deleteResult ? StringResources.Language.FileDeleteSuccess : StringResources.Language.FileDeleteFailed
                        ).IsSuccess)
                {
                    socket?.Close( );
                }

                if (deleteResult)
                {
                    LogNet?.WriteInfo(ToString( ), StringResources.Language.FileDeleteSuccess + ":" + relativeName);
                }
            }
            else if (customer == HslProtocol.ProtocolFileDirectoryFiles)
            {
                List <GroupFileItem> fileNames = new List <GroupFileItem>( );
                foreach (var m in GetDirectoryFiles(Factory, Group, Identify))
                {
                    FileInfo fileInfo = new FileInfo(m);
                    fileNames.Add(new GroupFileItem( )
                    {
                        FileName = fileInfo.Name,
                        FileSize = fileInfo.Length,
                    });
                }

                Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(fileNames.ToArray( ));
                if (SendStringAndCheckReceive(
                        socket,
                        HslProtocol.ProtocolFileDirectoryFiles,
                        jArray.ToString( )).IsSuccess)
                {
                    socket?.Close( );
                }
            }
            else if (customer == HslProtocol.ProtocolFileDirectories)
            {
                List <string> folders = new List <string>( );
                foreach (var m in GetDirectories(Factory, Group, Identify))
                {
                    DirectoryInfo directory = new DirectoryInfo(m);
                    folders.Add(directory.Name);
                }

                Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray( ));
                if (SendStringAndCheckReceive(
                        socket,
                        HslProtocol.ProtocolFileDirectoryFiles,
                        jArray.ToString( )).IsSuccess)
                {
                    socket?.Close( );
                }
            }
            else
            {
                socket?.Close( );
            }
        }
        /// <summary>
        /// 系统的登录方法
        /// </summary>
        /// <param name="obj">接收的socket对象</param>
        protected override void ThreadPoolLogin(object obj)
        {
            Socket socket = obj as Socket;

            try
            {
                OperateResult <byte[]> receive = Receive(socket, 4);
                if (!receive.IsSuccess)
                {
                    return;
                }

                byte[] ReceiveByte = receive.Content;
                int    Protocol    = BitConverter.ToInt32(ReceiveByte, 0);

                if (Protocol == 0x1001 || Protocol == 0x1002)
                {
                    // 安装系统和更新系统
                    if (Protocol == 0x1001)
                    {
                        LogNet?.WriteInfo(ToString(), StringResources.Language.SystemInstallOperater + ((IPEndPoint)socket.RemoteEndPoint).Address.ToString());
                    }
                    else
                    {
                        LogNet?.WriteInfo(ToString( ), StringResources.Language.SystemUpdateOperater + ((IPEndPoint)socket.RemoteEndPoint).Address.ToString());
                    }
                    if (Directory.Exists(FileUpdatePath))
                    {
                        string[] files = Directory.GetFiles(FileUpdatePath);

                        List <string> Files = new List <string>(files);
                        for (int i = Files.Count - 1; i >= 0; i--)
                        {
                            FileInfo finfo = new FileInfo(Files[i]);
                            if (finfo.Length > 200000000)
                            {
                                Files.RemoveAt(i);
                            }
                            if (Protocol == 0x1002)
                            {
                                if (finfo.Name == this.updateExeFileName)
                                {
                                    Files.RemoveAt(i);
                                }
                            }
                        }
                        files = Files.ToArray();

                        socket.BeginReceive(new byte[4], 0, 4, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);

                        socket.Send(BitConverter.GetBytes(files.Length));
                        for (int i = 0; i < files.Length; i++)
                        {
                            // 传送数据包含了本次数据大小,文件数据大小,文件名(带后缀)
                            FileInfo finfo    = new FileInfo(files[i]);
                            string   fileName = finfo.Name;
                            byte[]   ByteName = Encoding.Unicode.GetBytes(fileName);

                            int    First     = 4 + 4 + ByteName.Length;
                            byte[] FirstSend = new byte[First];

                            FileStream fs = new FileStream(files[i], FileMode.Open, FileAccess.Read);

                            Array.Copy(BitConverter.GetBytes(First), 0, FirstSend, 0, 4);
                            Array.Copy(BitConverter.GetBytes((int)fs.Length), 0, FirstSend, 4, 4);
                            Array.Copy(ByteName, 0, FirstSend, 8, ByteName.Length);

                            socket.Send(FirstSend);
                            Thread.Sleep(10);

                            byte[] buffer = new byte[4096];
                            int    sended = 0;
                            while (sended < fs.Length)
                            {
                                int count = fs.Read(buffer, 0, 4096);
                                socket.Send(buffer, 0, count, SocketFlags.None);
                                sended += count;
                            }

                            fs.Close();
                            fs.Dispose();

                            Thread.Sleep(20);
                        }
                    }
                }
                else
                {
                    // 兼容原先版本的更新,新的验证方式无需理会
                    socket.Send(BitConverter.GetBytes(10000f));
                    Thread.Sleep(20);
                    socket?.Close();
                }
            }
            catch (Exception ex)
            {
                Thread.Sleep(20);
                socket?.Close();
                LogNet?.WriteException(ToString( ), StringResources.Language.FileSendClientFailed, ex);
            }
        }