Esempio n. 1
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                Packet packetObj = (Packet)ar.AsyncState;
                Socket client    = packetObj.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    if (!packetObj.isCorrectPack)
                    {
                        PacketBuilder.UnPackParam(packetObj.buffer, out var crc, out var dataLen, out var category, out var command);
                        if (crc == PacketBuilder.crcCode)
                        {
                            packetObj.SetFirstReceive(dataLen, category, command);
                        }
                        else
                        {
                            //如果CRC不對就不動作(先不關閉)
                            Program.mainUI.OnShowSystemLog("CRC check fail");
                            throw new Exception();
                        }
                    }
                    //將收到的封包複製到infoBytes,從最後收到的位置
                    Array.Copy(packetObj.buffer, 0, packetObj.infoBytes, packetObj.LastReceivedPos, bytesRead);
                    //減去已收到的封包數
                    //接收完後更新對應的LastReceivedPos
                    packetObj.SetContiuneReceive(bytesRead);

                    if (packetObj.ReceiveLen == 0)
                    {
                        //傳送資料給對應的Command,扣掉前面的CRC,DataLen,Command
                        var pack = packetObj.infoBytes.Skip(PacketBuilder.VerificationLen).ToArray();
                        Program.mainUI.OnShowSystemLog($"SystemCategory={packetObj.SystemCategory}, SystemCommand={packetObj.SystemCommand}");
                        if (_SystemDict.TryGetValue(packetObj.SystemCategory, out var baseClientSystem))
                        {
                            baseClientSystem.PlayerEnter(packetObj.SystemCommand, pack);
                        }
                        else
                        {
                            Program.mainUI.OnShowSystemLog("Not mapping function.");
                        }

                        //接收完成
                        receiveDone.Set();
                        //開始接收新的封包
                        Receive();
                        receiveDone.WaitOne();
                    }
                    else
                    {
                        client.BeginReceive(packetObj.buffer, 0, Packet.BufferSize, 0,
                                            new AsyncCallback(ReceiveCallback), packetObj);
                    }
                }
            }
            catch (Exception e)
            {
                Program.mainUI.OnShowSystemLog(e.ToString());
            }
        }