示例#1
0
        // Wysyła żądania do serwera i obsługuje odpowiedzi.
        // Zwraca wysłany komunikat, odebrany komunikat od serwera i odpowiedź.
        public Tuple <string, string, string> Run(OperationCommand Parameters)
        {
            // Tworzenie wiadomości na podstawie danych podanych przez użytkownika.
            Message message       = server.CreateMessageRequest(Parameters);
            string  messageString = MessageSerializer.Serialize(message); // Serializacja komunikatu do formy z zadania klucz#wartość.

            data = Encoding.ASCII.GetBytes(messageString);

            // Komunikat zostaje wysłany jako pojedynczy pakiet. W przypadku klasy UdpSocket nie ma potrzeby jawnego przekazywania punktu końcowego
            // jeśli został zdefiniowany w konstruktorze.
            socket.Send(data, data.Length);
            string sended = ($"> {ipep.ToString()}: {Encoding.ASCII.GetString(data)}");

            data = socket.Receive(ref ipep);
            string stringData = Encoding.ASCII.GetString(data, 0, data.Length);
            string received   = ($"< {ipep.ToString()}: {stringData}");

            // Obsługa odpowiedzi.
            Message response     = MessageSerializer.Deserialize(stringData); // Deserializacja odpowiedzi od serwera.
            string  responsedata = "blad";

            if (response != null && response.Fields != null)
            {
                response.Fields.TryGetValue(ProtocolStrings.ResultField, out responsedata);
            }

            return(new Tuple <string, string, string>(sended, received, responsedata));
        }
示例#2
0
        public async Task <Operation> StartNew(OperationCommand operationCommand, Guid vmId)
        {
            if (operationCommand == null)
            {
                throw new ArgumentNullException(nameof(operationCommand));
            }

            var operation = new Operation
            {
                Id          = Guid.NewGuid(),
                MachineGuid = vmId,
                Status      = OperationStatus.Queued
            };

            _db.Add(operation);

            await _db.SaveChangesAsync().ConfigureAwait(false);

            if (vmId != Guid.Empty && (operationCommand is IMachineCommand machineCommand) &&
                machineCommand.MachineId != vmId)
            {
                machineCommand.MachineId = vmId;
            }


            operationCommand.OperationId = operation.Id;
            var commandJson = JsonConvert.SerializeObject(operationCommand);

            await _bus.Send(
                new StartOperation(operationCommand.GetType().AssemblyQualifiedName, commandJson, operation.Id)
                ).ConfigureAwait(false);

            return(operation);
        }
示例#3
0
        /// <summary>
        /// 按固定频率向客户端广播帧
        /// </summary>
        private void SendFrame()
        {
            long frame       = mCurrentFrame++;
            int  playerCount = 0; //当前帧有多少个客户端发了命令
            BroadPlayerFrameCommand sendData = new BroadPlayerFrameCommand();

            sendData.Frame     = frame;
            sendData.Frametime = mFrameTime;

            if (mFrameDic.ContainsKey(frame))
            {
                Dictionary <int, List <Command> > frames = mFrameDic[frame];

                playerCount = frames.Count;

                var it = frames.GetEnumerator(); // 循环访问构造器
                while (it.MoveNext())
                {
                    for (int i = 0, count = it.Current.Value.Count; i < count; ++i)
                    {
                        OperationCommand cmd = ProtoTransfer.Get(it.Current.Value[i]);
                        sendData.Commands.Add(cmd);
                    }
                }
            }


            //不显示那么多log
            if (frame % 30 == 0 || sendData.Commands.Count > 0)
            {
                Debug.Log(string.Format("Send frame:{0} user count:{1} command count:{2}", frame, playerCount, sendData.Commands.Count), ConsoleColor.Gray);
            }

            BroadCast(MessageID.BroadCmdFrame, sendData, true);
        }
        private void ShowJSON(string text, string source = "Root", bool skipJsonText = false)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(text))
                {
                    return;
                }

                tView.ClearTree();

                SettingsSingleton.Settings = VM.CSharp;

                var(IsValid, ValidJsonDoc, ErrorMessageDoc) = text.ParseJson();

                if (!IsValid)
                {
                    VM.JSONText = text;

                    tView.ProcessJson(ErrorMessageDoc, false, source);

                    return;
                }

                var overrideCommand = new OperationCommand(o => MessageBox.Show("Override"));

                // If we are sorting, C# will sort it, so process that first.
                VM.CSharpText = ValidJsonDoc.ToCSharpClassesString(VM.CSharp, overrideCommand);

                if (string.IsNullOrEmpty(VM.CSharp.Name))
                {
                    VM.CSharp.Name = VM.CSharp.ClassName;
                }

                VM.SQLTableText = ValidJsonDoc.ToSqlTableString(VM.CSharp, null);

                VM.SQLTableTypeText = ValidJsonDoc.ToSqlTableTypeString(VM.CSharp);

                VM.BlazoriseText = ValidJsonDoc.ToBlazoriseDataGridString(VM.CSharp);

                VM.ComponentText = ValidJsonDoc.ToComponentString(VM.CSharp);

                VM.SQLMergeText = ValidJsonDoc.ToSQLMergeString(VM.CSharp);

                tView.ProcessJson(ValidJsonDoc, false, source);

                tView.OpenFirstItem(true);

                if (!skipJsonText)
                {
                    VM.JSONText = (tView.Tag as JsonDocument).ToFormattedJsonString();
                }
            }
            catch (Exception ex)
            {
                VM.Error = ex.Demystify().ToString();
            }
        }
        private async Task <Unit> HandleError(PowershellFailure failure, OperationCommand command)
        {
            await _bus.Send(new OperationFailedEvent()
            {
                OperationId  = command.OperationId,
                ErrorMessage = failure.Message
            }).ConfigureAwait(false);

            return(Unit.Default);
        }
示例#6
0
        // Obsługa przycisku "wyślij".
        private void WyslijButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Obsługa błędu. Niepołączony klient chce wysłać wiadomość.
                if (!Connected)
                {
                    MessageBox.Show("Musisz być połączony z serwerem, aby wykonać operacje.", "Błąd połączenia");
                    return;
                }

                // Parsowanie danych podanych przez użytkownika.
                OperationCommand parameters = new OperationCommand();
                parameters.ParseInputNums(LiczbyTextBox.Text); // Liczby.

                // Obsługa błędu. Klient mając zaznaczoną opcję max 3 argumentów wpisuje ich więcej.
                if (Max3Numbers && parameters.NumsLength != 3)
                {
                    MessageBox.Show("Musisz wysłać dokładnie 3 liczby.\n" +
                                    "Odznacz opcję automatycznego wysyłania finalnego wyniku po 3 komunikatach jeśli chcesz kontynuować.", "Błąd wysyłania");
                    return;
                }

                // Obsługa błęduw. Brak argumentów liczbowych.
                if (string.IsNullOrEmpty(OperacjaComboBox.Text))
                {
                    MessageBox.Show("Przed wysłaniem wybierz operację na liczbach jaką chcesz wykonać.", "Błąd operacji");
                    return;
                }

                parameters.ParseInputOperation(OperacjaComboBox.Text.ToString()); // Parsowanie operacji.

                if (OstatniKomunikatCheckBox.Checked || Max3Numbers)              // Parsowanie - czy zwrócić wynik ostateczny.
                {
                    parameters.End = true;
                }
                else
                {
                    parameters.End = false;
                }

                Tuple <string, string, string> packetsTuple = this.Client.Run(parameters);

                OstatnieKomunikatyWypiszTextBox.Text = packetsTuple.Item1 + Environment.NewLine + Environment.NewLine + packetsTuple.Item2;
                WynikOdpowiedzLabel.Text             = packetsTuple.Item3.ToString();
            }
            catch (FormatException fEx)
            {
                MessageBox.Show(fEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void RegisterCommand()
        {
            if (UpCommand == null)
            {
                UpCommand = new OperationCommand(param => Up(), param => CanMoveup());

                DownCommand   = new OperationCommand(param => Down(), param => CanMovedown());
                BottomCommand = new OperationCommand(param => Bottom(), param => CanMovedown());
                TopCommand    = new OperationCommand(param => Top(), param => CanMoveup());
            }
        }
示例#8
0
        public static OperationCommand Get(Command command)
        {
            OperationCommand cmd = new OperationCommand()
            {
                Id        = command.Id,
                Frame     = command.Frame,
                Frametime = command.Time,
                Type      = command.Type,
                Data      = Google.Protobuf.ByteString.CopyFrom(command.Data),
            };

            return(cmd);
        }
示例#9
0
        // Tworzy komunikat z zapytaniem o operację.
        public Message CreateMessageRequest(OperationCommand cmd)
        {
            Message message = CreateMessageRequest();

            if (cmd != null)
            {
                message.Fields[ProtocolStrings.OperationField] = cmd.Operation.ToString();

                for (int i = 1; i <= cmd.Nums.Count; i++)
                {
                    message.Fields[$"{ProtocolStrings.ArgField}{i}"] = cmd.Nums.ElementAt(i - 1).ToString();
                }

                message.Fields[ProtocolStrings.ArgCounterField] = cmd.NumsLength.ToString();
            }

            message.Fields[ProtocolStrings.RequestField] = ProtocolStrings.RequestFieldOperationAction;
            message.Fields[ProtocolStrings.End]          = cmd.End.ToString();

            return(message);
        }
示例#10
0
        public TransactionService
        (
            IPlayerRepository playerRepository,
            ITransactionRepository transactionRepository,
            IBalanceRepository balanceRepository,
            IUnitOfWork unitOfWork
        )
        {
            _playerRepository      = playerRepository;
            _transactionRepository = transactionRepository;
            _balanceRepository     = balanceRepository;
            _unitOfWork            = unitOfWork;
            var operationCommand = new OperationCommand
            {
                DepositDelegate = Deposit,
                StakeDelegate   = Stake,
                WinDelegate     = Win
            };

            _transactionCommand = new TransactionCommand(operationCommand);
        }
示例#11
0
 public MainWindow()
 {
     OperationCommand.Register();
     InitializeComponent();
     DataContext = new Seal.Proxies.MyApplicationSession();
 }
示例#12
0
 public MainWindow()
 {
     OperationCommand.Register();
     InitializeComponent();
     DataContext = _mainSession;
 }
示例#13
0
 public Task <Operation> StartNew(OperationCommand operationCommand)
 {
     return(StartNew(operationCommand, Guid.Empty));
 }
示例#14
0
        // 帧同步  ----->收到所有玩家的操作帧之后  进行帧的驱动
        private void OnLockStepFrame(Session client, PlayerFrameCommand recvData)
        {
            long frame  = recvData.Frame;
            int  roleId = recvData.RoleId;

            if (recvData.Commands.Count > 0 || frame % 30 == 0)
            {
                Debug.Log(string.Format("Receive {0} serverframe:{1} clientframe:{2} command:{3}", roleId, mCurrentFrame, frame, recvData.Commands.Count), ConsoleColor.DarkGray);
            }
            if (mFrameDic.ContainsKey(frame) == false)
            {
                // 添加到当前帧的玩家操作指令中
                mFrameDic.Add(frame, new Dictionary <int, List <Command> >());
            }

            var frames = mFrameDic[frame];

            //当前帧的服务器命令
            if (frames.ContainsKey(SERVER_ROLEID) == false)
            {
                frames.Add(SERVER_ROLEID, new List <Command>());
            }

            //该玩家是否发送了当前帧
            if (frames.ContainsKey(roleId) == false)
            {
                frames.Add(roleId, new List <Command>());
            }

            for (int i = 0; i < recvData.Commands.Count; ++i)
            {
                Command cmd = new Command(recvData.Commands[i].Frame, recvData.Commands[i].Type, recvData.Commands[i].Data.ToByteArray(), recvData.Commands[i].Frametime);

                frames[roleId].Add(cmd);
            }

            //当所有玩家都发送了该帧,就可以广播了
            //减去1是因为服务器命令也在当前帧中
            if (frames.Count - 1 >= mPlayerList.Count)
            {
                BroadPlayerFrameCommand sendData = new BroadPlayerFrameCommand();
                sendData.Frame     = frame;
                sendData.Frametime = mFrameTime;
                var it = frames.GetEnumerator();
                while (it.MoveNext())
                {
                    for (int i = 0, count = it.Current.Value.Count; i < count; ++i)
                    {
                        OperationCommand cmd = ProtoTransfer.Get(it.Current.Value[i]);
                        sendData.Commands.Add(cmd);
                    }
                }


                BroadCast(MessageID.BroadCmdFrame, sendData, true);

                mCurrentFrame = frame + 1;
            }
            else
            {
                Debug.Log(string.Format("Waiting {0} frame:{1} count:{2} current:{3} ", roleId, frame, mFrameDic[frame].Count, mPlayerList.Count), ConsoleColor.Red);
            }
        }