public void Start(ServerCommand command) { switch (command.Type) { case CommandType.Blocked: var method = new BlockedMethod(); method.SetParams(int.Parse(command.Parameters[1]), int.Parse(command.Parameters[2])); method.Execute(command.Parameters); break; case CommandType.GetMatrixs: new MatrixHelper().Start(int.Parse(command.Parameters[1]), int.Parse(command.Parameters[2])); break; case CommandType.Unblocked: var umethod = new UnblockedMedhod(); umethod.SetParams(int.Parse(command.Parameters[1]), int.Parse(command.Parameters[2])); umethod.Execute(command.Parameters); break; case CommandType.Group: var gmethod = new GroupMethod(); gmethod.SetParams(int.Parse(command.Parameters[1]), int.Parse(command.Parameters[2]), int.Parse(command.Parameters[3])); gmethod.Execute(command.Parameters); break; case CommandType.Unknown: break; } }
public bool ContinueExecuteCommandThreading(Socket socket, ServerCommand command, Socket socketUDPWrite, Socket socketUDPRead, TripleEndPointModel endPoint) { switch (command.Type) { case CommandType.DownloadUDP: while (true) { if (downloadService.ContinueExecute(socket, endPoint.EndPointUDPWrite, endPoint.EndPointUDPRead, socketUDPWrite, socketUDPRead, command, ProtocolType.Udp)) { break; } } ; break; case CommandType.UploadUDP: while (true) { if (uploadService.ContinueExecute(socket, endPoint.EndPointUDPRead, endPoint.EndPointUDPWrite, socketUDPRead, socketUDPWrite, command, ProtocolType.Udp)) { break; } } ; break; } return(false); }
private void DownloadFileUDP(ServerCommand command) { try { var file = File.OpenRead(command.Parameters.First()); var fileModel = new FileModel() { FileName = file.Name, Size = file.Length }; long packetNumber = 0, partCamingPackets = 0; socket.Send(new byte[4096].InsertInStartArray(Encoding.ASCII.GetBytes($"{file.Length}|"))); while (file.Length > fileModel.Packets.Where(x => x.IsCame).Sum(x => x.Size)) { while (fileModel.Packets.Where(x => x.IsSend).Sum(x => x.Size) < file.Length && partCamingPackets < 16) { packetNumber = FirstSending(file, fileModel, packetNumber); partCamingPackets++; } partCamingPackets = 0; while (fileModel.Packets.Any(x => x.IsCame == false)) { ResendingMissingPackets(file, fileModel); } } file.Close(); } catch (FileNotFoundException ex) { var response = new byte[4096].InsertInStartArray(Encoding.ASCII.GetBytes($"Error|")); socket.Send(response); Console.WriteLine(ex); } }
private bool CheckForDeleteCheaterCommand(PlayerChatEventArgs args) { if (args.IsServerMessage || args.Text.IsNullOrTimmedEmpty()) { return(false); } ServerCommand command = ServerCommand.Parse(args.Text); if (!command.Is(Command.DeleteCheater) || command.PartsWithoutMainCommand.Count == 0) { return(false); } string login = command.PartsWithoutMainCommand[0]; if (!LoginHasRight(args.Login, true, Command.DeleteCheater)) { return(true); } if (PlayerAdapter.RemoveAllStatsForLogin(login)) { SendFormattedMessageToLogin(args.Login, Settings.CheaterDeletedMessage, "Login", login); DetermineLocalRecords(); OnLocalRecordsDetermined(new List <RankEntry>(LocalRecords)); } else { SendFormattedMessageToLogin(args.Login, Settings.CheaterDeletionFailedMessage, "Login", login); } return(true); }
private void Login(string[] args) { if ((int)ServerConfigManager.MyConfigs["maxUserCount"] == CurrServerDB.getLoggedUserCount()) { CurrClient.Send((int)ServerCommand.ServerIsFull); } if (CurrClient.UserID != "") { CurrClient.Send((int)ServerCommand.AlreadyLogged); return; } //if ((bool)ServerConfigManager.MyConfigs["isServerPrivate"]) { CurrClient.Send((int)ServerCommand.ServerIsPrivate); return; } if (args.Length == 2) { string username = args[0]; string password = args[1]; ServerCommand cmd = CurrServerDB.Login(username, password); if (cmd == ServerCommand.isLogged) { CurrClient.UserID = CurrServerDB.getIdByUsername(username).ToString(); } if (cmd == ServerCommand.NewUserRegistered) { CurrClient.UserID = CurrServerDB.getIdByUsername(username).ToString(); } CurrClient.Send((int)cmd); } else { Console.WriteLine("Zu viele Parameter beim Login: " + CurrClient.EndPoint.ToString()); CurrClient.Send((int)ServerCommand.WrongArgs); } }
public object ExecuteR(CommandRequest cmd, bool hasReturn, bool hasUAReturn) { UAReturn r; ServerCommand srvCMD = new ServerCommand(_userSession.DefaultDispatcher, "", cmd.CommandSyntax); return(srvCMD.ExecuteR(hasReturn, hasUAReturn)); }
private void HandleServerCommand(ServerCommand command) { switch (command.Type) { case ServerCommandType.PRI: HandlePrivateMessage(command, command.Value <string>("character")); break; case ServerCommandType.MSG: case ServerCommandType.LRP: HandleChannelMessage(command, command.Value <string>("character")); break; case ServerCommandType.RLL: var rll = command.Payload.ToObject <ServerRll>(); if (rll.channel == null) { HandlePrivateMessage(command, rll.character); } else { HandleChannelMessage(command, rll.character); } break; case ServerCommandType.TPN: var tpn = command.Payload.ToObject <ServerTpn>(); characterManager.GetCharacter(tpn.character).TypingStatus = tpn.status; break; } }
private void Callbacks_PlayerChat(object sender, Communication.EventArguments.Callbacks.PlayerChatEventArgs e) { if (e.IsServerMessage) { return; } RunCatchLog(() => { string text = e.Text.ToLower(CultureInfo.InvariantCulture); ServerCommand command = ServerCommand.Parse(e.Text); if (ProRestartCommands.Contains(text) || command.Is(Command.ProRestart)) { if (ConsiderLogin(e.Login, true)) { SendFormattedMessageToLogin(e.Login, "{[#ServerStyle]}>{[#MessageStyle]} Your vote for track restart was considered."); SendStatisticsToLogin(e.Login); } return; } if ((ConRestartCommands.Contains(text) || command.Is(Command.ConRestart)) && ConsiderLogin(e.Login, false)) { SendFormattedMessageToLogin(e.Login, "{[#ServerStyle]}>{[#MessageStyle]} Your vote against track restart was considered."); SendStatisticsToLogin(e.Login); } }, "Error in PlayerChat Callback.", true); }
private void HandlePrivateMessage(ServerCommand command, string character) { var sender = characterManager.GetCharacter(character); sender.TypingStatus = TypingStatusEnum.Clear; if (sender.IsIgnored) { chatManager.Send(Helpers.CreateClientCommand(ClientCommandType.IGN, new ClientIgn { action = ClientIgn.Action.notify, character = sender.Name })); return; } var message = command.Value <string>("message"); switch (command.Type) { case ServerCommandType.PRI: CharacterMessageReceived?.Invoke(sender, CreateMessage(sender, command.Time, WebUtility.HtmlDecode(message))); break; case ServerCommandType.RLL: CharacterMessageReceived?.Invoke(sender, new Message(Message.Type.Roll, sender, command.Time, message.Substring(message.IndexOf("[/user]" + 7)))); break; } }
private void HandleChannelMessage(ServerCommand command, string character) { var sender = characterManager.GetCharacter(character); if (sender.IsIgnored) { return; } var channel = channelManager.JoinedChannels[command.Value <string>("channel")]; var message = command.Value <string>("message"); switch (command.Type) { case ServerCommandType.MSG: ChannelMessageReceived?.Invoke(channel, CreateMessage(sender, command.Time, WebUtility.HtmlDecode(message))); break; case ServerCommandType.LRP: ChannelMessageReceived?.Invoke(channel, new Message(Message.Type.Ad, sender, command.Time, WebUtility.HtmlDecode(message))); break; case ServerCommandType.RLL: ChannelMessageReceived?.Invoke(channel, new Message(Message.Type.Roll, sender, command.Time, message.Substring(message.IndexOf("[/user]" + 7)))); break; } }
public void Command(ServerCommand commandIndex) { Type thisType = this.GetType(); MethodInfo theMethod = thisType.GetMethod(commandIndex.ToString()); theMethod.Invoke(this, null); }
private bool CheckForSelectUndrivenTracksCommand(PlayerChatEventArgs args) { ServerCommand serverCommand = ServerCommand.Parse(args.Text); if (!serverCommand.Is(Command.SelectUndrivenTracks)) { return(false); } if (!LoginHasRight(args.Login, true, Command.SelectUndrivenTracks)) { return(true); } string targetLogin = args.Login; if (serverCommand.HasFurtherParts) { targetLogin = serverCommand.PartsWithoutMainCommand[0]; } PlayerSettings playerSettings = GetPlayerSettings(targetLogin); if (playerSettings == null) { SendNoPlayerWithLoginMessageToLogin(args.Login, targetLogin); return(true); } SelectUndrivenTracks(args.Login, targetLogin); return(true); }
private void OnCommandReceived(ServerCommand serverCommand) { if (serverCommand.Type == ServerCommandType.FRL) { frl = serverCommand; } }
private void OnCommandReceived(ServerCommand command) { switch (command.Type) { case ServerCommandType.JCH: var jch = command.Payload.ToObject <ServerJch>(); if (jch.character.identity == chatManager.OwnCharacterName) { var memberList = new ObservableKeyedList <Character, Channel.Member>(x => x.Character); var newChannel = new Channel(jch.channel, jch.title, memberList); members.Add(newChannel, memberList); joinedChannels.Add(newChannel); SetIsJoined(newChannel, true); return; } break; case ServerCommandType.ICH: case ServerCommandType.CDS: case ServerCommandType.CBU: case ServerCommandType.CKU: case ServerCommandType.COA: case ServerCommandType.COL: case ServerCommandType.COR: case ServerCommandType.CSO: case ServerCommandType.CTU: case ServerCommandType.LCH: case ServerCommandType.RMO: break; case ServerCommandType.FLN: var flnCharacter = command.Value <string>("character"); foreach (var item in joinedChannels.ToList()) { members[item].Remove(characterManager.GetCharacter(flnCharacter)); } return; case ServerCommandType.CHA: publicChannels.Reset(command.Payload.GetValue("channels").Select(x => { var name = x.Value <string>("name"); var item = new ChannelListItem(name, name, x.Value <int>("characters")); item.IsJoined = JoinedChannels.ContainsKey(item.Id); return(item); })); return; case ServerCommandType.ORS: privateChannels.Reset(command.Payload.GetValue("channels").Select(x => { var item = new ChannelListItem(x.Value <string>("name"), x.Value <string>("title"), x.Value <int>("characters")); item.IsJoined = JoinedChannels.ContainsKey(item.Id); return(item); })); return; default: return; } HandleChannelMessage(joinedChannels[command.Value <string>("channel")], command); }
void WhenSendingServerCommandAsJson(ServerCommand serverCommand) { _browser.Put(UrlList.ServerControlPoint_absPath, with => { with.JsonBody(serverCommand); with.Accept("application/json"); }); }
internal override void Process() { if (this.Commands != null) { while (this.Commands.Count != 0) { Command Command = this.Commands[0]; if (Command.ExecuteSubTick > this.Device.GameMode.Time.ClientSubTick) { if (Command.IsServerCommand) { ServerCommand ServerCommand = (ServerCommand)Command; if (ServerCommand.Id != -1) { if (this.Device.GameMode.CommandManager.ServerCommands.TryGetValue(ServerCommand.Id, out ServerCommand Original)) { if (Original.Checksum != ServerCommand.Checksum) { goto Remove; } } else { goto Remove; } } else { goto Remove; } } this.Device.GameMode.Time.ClientSubTick = Command.ExecuteSubTick; this.Device.GameMode.Tick(); Command.Execute(this.Device.GameMode); } else { Logging.Error(this.GetType(), "Execute command failed! Command should be already executed. (client_subtick=" + Command.ExecuteSubTick + " server_subtick=" + this.Device.GameMode.Time.ClientSubTick + ")"); } Remove: this.Commands.RemoveAt(0); } } this.Device.GameMode.Time.ClientSubTick = this.SubTick; this.Device.GameMode.Tick(); if (this.Device.GameMode.Checksum != this.Checksum) { Logging.Error(this.GetType(), "Client - Server are Out Of Sync! (client_checksum:" + this.Checksum + " server_checksum:" + this.Device.GameMode.Checksum + ")"); new Out_Of_Sync_Message(this.Device).Send(); } }
public UAReturn LogCommandNotExecute(CommandRequest cmd)//16Aug2016 { UAReturn r; ServerCommand srvCMD = new ServerCommand(_userSession.DefaultDispatcher, "", cmd.CommandSyntax); srvCMD.JustLogCommandDoNotExecute(); return(srvCMD.Result); }
public void prepareNewMessage4Client(MessageType msgType, ServerCommand cmd) { if (msgType == MessageType.Command) { string msgContent = msgType.ToString() + paramSeperators + cmd.ToString() + paramSeperators; sendMessage(msgContent); } }
public void Send(ServerCommand _command, string _data) { byte[] packet = System.Text.Encoding.Unicode.GetBytes(_command.ToString( ) + ";" + _data + ";"); try { listener.Send(packet, packet.Length, SocketFlags.None); } catch (Exception e) { MessageBox.Show("Hálózati hiba az üzenet küldése során!\n" + e.Message, "Hiba!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public UAReturn Execute(CommandRequest cmd) { UAReturn r; ServerCommand srvCMD = new ServerCommand(_userSession.DefaultDispatcher, "", cmd.CommandSyntax); srvCMD.Execute(); return(srvCMD.Result); }
/// <summary>Registers a User</summary> public static String RegisterUser(String Pin, String Username, bool Corporate) { if (Corporate) { return(ServerCommand.RawCommand("REG" + Pin + "," + Username + " (Corp.)")); } return(ServerCommand.RawCommand("REG" + Pin + "," + Username)); }
public void ParseAndQueueServerCommands(JSONArray commands) { foreach (JSONNode commandNode in commands) { var sc = new ServerCommand(commandNode); serverCommandQueue.Enqueue(sc); } }
private bool UploadFileUDPContinue(ServerCommand command) { FileStream file = null; udpModel = fileModels.FirstOrDefault(x => x.socket == socket); if (udpModel == null) { file = File.OpenWrite(command.Parameters.First()); udpModel = new FileModel() { FileName = file.Name, Size = long.Parse(command.Parameters[1]), socket = socket, fileStream = file }; fileModels.Add(udpModel); if (file.Length > 0) { var fileName = file.Name; file.Close(); File.Delete(fileName); file = File.OpenWrite(fileName); udpModel.fileStream = file; } return(false); } file = udpModel.fileStream; if (file.Length >= udpModel.Size) { file.Close(); return(true); } if (udpModel.PacketCount == 16) { udpModel.PacketCount = 0; socketUDPWrite.SendTo(Encoding.ASCII.GetBytes("Correct"), endPointWrite); return(file.Length == udpModel.Size); } socketUDP.ReceiveTimeout = 1000; try { FirstDataGetting(file); }catch (Exception exc) { socketUDPWrite.SendTo(Encoding.ASCII.GetBytes(udpModel.Packets.Last().Number.ToString()), endPointWrite); return(file.Length >= udpModel.Size); } socketUDP.ReceiveTimeout = 0; udpModel.PacketCount++; var filelength = file.Length; if (file.Length >= udpModel.Size) { fileModels.Remove(udpModel); file.Close(); } return(filelength >= udpModel.Size); }
private void Callbacks_PlayerChat(object sender, Communication.EventArguments.Callbacks.PlayerChatEventArgs e) { RunCatchLog(() => { ServerCommand command = ServerCommand.Parse(e.Text); if (!command.Is(Command.Donate) || command.PartsWithoutMainCommand.Count == 0) { return; } int coppers; if (!int.TryParse(command.PartsWithoutMainCommand[0], NumberStyles.None, CultureInfo.InvariantCulture, out coppers) || coppers <= 0) { return; } if (coppers < Settings.MinDonationValue) { SendFormattedMessageToLogin(e.Login, Settings.DonationToSmallMessage, "Coppers", Settings.MinDonationValue.ToString(CultureInfo.InvariantCulture)); return; } PlayerSettings playerSettings = GetPlayerSettings(e.Login); bool isUnitedAccount = playerSettings.IsUnitedAccount; if (!playerSettings.DetailMode.HasDetailedPlayerInfo()) { DetailedPlayerInfo playerInfo = GetDetailedPlayerInfo(e.Login); if (playerInfo != null) { isUnitedAccount = playerInfo.IsUnitedAccount; } } if (!isUnitedAccount) { SendFormattedMessageToLogin(e.Login, Settings.PlayerHasNoUnitedAccountMessage); return; } GenericResponse <int> billResponse = Context.RPCClient.Methods.SendBill(e.Login, coppers, Settings.DonationHint, Settings.DonationTargetLogin); if (billResponse.Erroneous) { Logger.Warn(string.Format("Error while calling method SendBill: {0}({1})", billResponse.Fault.FaultMessage, billResponse.Fault.FaultCode)); SendFormattedMessageToLogin(e.Login, Settings.DonationErrorMessage, "ErrorMessage", billResponse.Fault.FaultMessage); return; } BillDictionary[billResponse.Value] = new DonationInfo { Login = e.Login, Coppers = coppers }; }, "Error in Callbacks_PlayerChat Method.", true); }
void OnDataReceived(NetBuffer msg) { byte code = msg.ReadByte(); ServerCommand command = (ServerCommand)code; CommandsToDo.AddLast(Utilities.MakePair <ServerCommand, NetBuffer>(command, msg)); ExecuteCommands(); }
public void Process(ServerCommand command) { var characterObj = Instantiate(shipPrefab) as GameObject; var character = characterObj.GetComponent <Ship>(); command.onProcessedCallback.Invoke(); }
public async Task <IActionResult> ReturnResponse(ServerCommand service, object success, object error) { if (service.HasNotifications()) { return(BadRequest(new { success = false, data = error, errors = service.GetNotifications() })); } return(Ok(new { success = true, data = success })); }
public void SendMoveCommand(CellCoord moveCoord) { ServerCommand command = new ServerCommand(CommandType.MOVE) { MoveCoord = moveCoord }; SendCommand(command); }
public void CommandInfoConstructorTest() { ServerCommand id = ServerCommand.Keywords; short version = 1; CommandInfo target = new CommandInfo(id, version); Assert.AreEqual(version, target.Version); Assert.AreEqual(id, target.Id); }
public void SendRestartCommand(string winnerNickname) { ServerCommand command = new ServerCommand(CommandType.RESTART) { OpponentName = winnerNickname }; SendCommand(command); }
void GivenFirstTestWorkflow(string alternativeName) { var serverCommand = new ServerCommand { Command = ServerControlCommands.LoadConfiguraiton, Data = alternativeName }; _browser.Put(UrlList.ServerControlPoint_absPath, with => { with.JsonBody(serverCommand); with.Accept("application/json"); }); }
/// <summary> /// Creates a new Command instance /// </summary> /// <param name="condition"></param> /// <param name="clientExecution">The method that will be executed</param> /// <param name="serverExecution"></param> /// <param name="applyServerResult"></param> /// <param name="comandType">The CommandType of this Command</param> /// <param name="networkValueType">The type of the value that is returned by the Execution delegate, if the command doesn't returns a value, you can set this to null to limit network data transfer</param> /// <param name="dataTransferOptions">Defines options for network packet transmission</param> /// <param name="frequency">Defines the frequency at which the current command will be processed</param> public Command(Condition condition, ClientCommand clientExecution, ServerCommand serverExecution, ApplyServerCommand applyServerResult, CommandType comandType, Type networkValueType, DataTransferOptions dataTransferOptions, ExecutionFrequency frequency) { if (networkValueType != null && !networkValueType.IsValueType && networkValueType != typeof(string) && networkValueType != typeof(byte[])) throw new CoreException("DataType must be a ValueType."); LocalId = _count++; Condition = condition; ClientExecution = clientExecution; ServerExecution = serverExecution; ApplyServerResult = applyServerResult; Type = comandType; NetworkValueType = networkValueType; TransferOptions = dataTransferOptions; Frequency = frequency; }
internal void DispatchServerCommand(ZonePlayer zp, ServerCommand cmd, Dictionary<string, string> args) { switch (cmd) { case ServerCommand.Zone: Zone zone; using (EmuDataContext dbCtx = new EmuDataContext()) { dbCtx.ObjectTrackingEnabled = false; zone = dbCtx.Zones.SingleOrDefault(z => z.ShortName == args["name"]); } if (zone != null) MovePlayer(zp, zone.ZoneID, 0u, zone.SafeX, zone.SafeY, zone.SafeZ, 0.0f, ZoneMode.ZoneToSafeCoords); else zp.MsgMgr.SendSpecialMessage(MessageType.Default, "Unable to locate zone " + args["name"]); break; case ServerCommand.GoTo: break; default: break; } }
/// <summary> /// Sends a player command to a client. /// </summary> /// <param name="fillMessage">The function to call to fill the message with the command</param> void SendCommand(NetConnection connection, ServerCommand command, NetDeliveryMethod method, Action<NetOutgoingMessage> fillMessage) { NetOutgoingMessage msg = NetServer.CreateMessage(); msg.Write((byte)command); fillMessage(msg); NetServer.SendMessage(msg, connection, method); }
/// <summary> /// Sends a server command to the publisher connection. /// </summary> /// <param name="commandCode"><see cref="ServerCommand"/> to send.</param> /// <param name="data">Optional command data to send.</param> /// <returns><c>true</c> if <paramref name="commandCode"/> transmission was successful; otherwise <c>false</c>.</returns> public virtual bool SendServerCommand(ServerCommand commandCode, byte[] data = null) { if ((object)m_commandChannel != null && m_commandChannel.CurrentState == ClientState.Connected) { try { using (BlockAllocatedMemoryStream commandPacket = new BlockAllocatedMemoryStream()) { // Write command code into command packet commandPacket.WriteByte((byte)commandCode); // Write command buffer into command packet if ((object)data != null && data.Length > 0) commandPacket.Write(data, 0, data.Length); // Send command packet to publisher m_commandChannel.SendAsync(commandPacket.ToArray(), 0, (int)commandPacket.Length); m_metadataRefreshPending = commandCode == ServerCommand.MetaDataRefresh; } return true; } catch (Exception ex) { OnProcessException(MessageLevel.Error, new InvalidOperationException($"Exception occurred while trying to send server command \"{commandCode}\" to publisher: {ex.Message}", ex)); } } else OnProcessException(MessageLevel.Error, new InvalidOperationException($"Subscriber is currently unconnected. Cannot send server command \"{commandCode}\" to publisher.")); return false; }
public ServerCommandEventArgs(Server server, ServerCommand command, string[] tokens) : base(server) { Command = command; Tokens = tokens; }
void AddRemarkableEvent(ServerCommand command, Action<NetBuffer> action) { RemarkableEvents.Add(Utilities.MakePair(command, action)); }
void CreateTestWorkflow(string testWorkflowName, string testWorkflowFileName) { var serverCommand = new ServerCommand { Command = ServerControlCommands.LoadConfiguraiton, Data = testWorkflowName }; _restTemplate.Put(UrlList.ServerControlPoint_absPath, serverCommand); var workflowLoader = new WorkflowLoader(); workflowLoader.Load(PathToWorkflows + testWorkflowFileName); }
public Command RegisterCommand (string name, CommandFunc func) { if (name == null) throw new ArgumentNullException ("name"); if (func == null) throw new ArgumentNullException ("func"); var c = new ServerCommand { Id = id++, Name = name, Function = func, }; commands.Add (c); SendCommand (c); return c; }
public static Command CreateServerCommand(ServerCommand serverCommand, ExecutionFrequency frequency) { return CreateServerCommand(null, serverCommand, frequency); }
void WhenSendingServerCommandAsXml(ServerCommand serverCommand) { _browser.Put(UrlList.ServerControlPoint_absPath, with => { with.JsonBody(serverCommand); with.Accept("application/xml"); }); }
public static Command CreateServerCommand(ServerCommand serverCommand) { return CreateServerCommand(null, serverCommand, ExecutionFrequency.FullUpdate60Hz); }
/// <summary> /// Sends a server command to the publisher connection. /// </summary> /// <param name="commandCode"><see cref="ServerCommand"/> to send.</param> /// <param name="data">Optional command data to send.</param> /// <returns><c>true</c> if <paramref name="commandCode"/> transmission was successful; otherwise <c>false</c>.</returns> public virtual bool SendServerCommand(ServerCommand commandCode, byte[] data = null) { if ((object)m_commandChannel != null && m_commandChannel.CurrentState == ClientState.Connected) { try { using (BlockAllocatedMemoryStream commandPacket = new BlockAllocatedMemoryStream()) { // Write command code into command packet commandPacket.WriteByte((byte)commandCode); // Write command buffer into command packet if ((object)data != null && data.Length > 0) commandPacket.Write(data, 0, data.Length); // Send command packet to publisher m_commandChannel.SendAsync(commandPacket.ToArray(), 0, (int)commandPacket.Length); m_metadataRefreshPending = (commandCode == ServerCommand.MetaDataRefresh); } // Track server command in pending request queue lock (m_requests) { // Make sure a pending request does not already exist int index = m_requests.BinarySearch(commandCode); if (index < 0) { // Add the new server command to the request list m_requests.Add(commandCode); // Make sure requests are sorted to allow for binary searching m_requests.Sort(); } } return true; } catch (Exception ex) { OnProcessException(new InvalidOperationException($"Exception occurred while trying to send server command \"{commandCode}\" to publisher: {ex.Message}", ex)); } } else OnProcessException(new InvalidOperationException($"Subscriber is currently unconnected. Cannot send server command \"{commandCode}\" to publisher.")); return false; }
public BaseCommand(ServerCommand serverCommand, string[] args) { this.ServerCommand = serverCommand; this.Args = args; }
// ReSharper restore FunctionNeverReturns private static void PlayerThread(NetworkPlayer player) { NetworkStream clientStream; //make all the introductions. we do this before sending the world so the client doesn't see them as new connections foreach (var otherPlayer in Players.Values) { try { new Connect(otherPlayer.Id, otherPlayer.UserName, otherPlayer.Coords) { ConnectedPlayer = player, Immediate = true }.Send(); } catch (Exception ex) { WriteToServerConsoleLog(string.Format("{0} {1} caused an exception and was removed: {2}", player.UserName, player.IpAddress, ex.Message)); #if DEBUG WriteToServerConsoleLog(ex.StackTrace); #endif } new Connect(player.Id, player.UserName, player.Coords) { ConnectedPlayer = otherPlayer }.Send(); } try { Players.TryAdd(player.Id, player); //note: it is not possible for the add to fail on ConcurrentDictionary, see: http://www.albahari.com/threading/part5.aspx#_Concurrent_Collections UpdateServerConsolePlayerList(); var getWorld = new GetWorld { ConnectedPlayer = player }; getWorld.Send(); WriteToServerConsoleLog(String.Format("World send complete to {0} ({1} compressed, {2} uncompressed)", player.IpAddress, getWorld.DataLength, getWorld.UncompressedLength)); //create a thread to handle communication with connected client player.TcpClient.NoDelay = true; clientStream = player.TcpClient.GetStream(); } catch (Exception ex) { HandleNetworkError(player, ex); return; } var actionTypebytes = new byte[sizeof(ushort)]; try { if (!string.IsNullOrWhiteSpace(Config.MOTD)) new ServerMsg(Config.MOTD, player).Send(); while (true) { Thread.Sleep(10); //bm: polling is expensive. don't remove this or the server will pin your machine when only a couple users are online GameAction gameAction; while (player.SendQueue.Count > 0 && player.SendQueue.TryDequeue(out gameAction)) { gameAction.Immediate = true; gameAction.Send(); } if (!clientStream.DataAvailable) continue; var bytesRead = 0; while (bytesRead < actionTypebytes.Length) bytesRead += clientStream.Read(actionTypebytes, bytesRead, actionTypebytes.Length - bytesRead); var actionType = (ActionType)BitConverter.ToUInt16(actionTypebytes, 0); switch (actionType) { case ActionType.AddBlock: gameAction = new AddBlock(); break; case ActionType.AddBlockItem: gameAction = new AddBlockItem(); break; case ActionType.AddBlockMulti: gameAction = new AddBlockMulti(); break; case ActionType.AddCuboid: gameAction = new AddCuboid(); break; case ActionType.AddProjectile: gameAction = new AddProjectile(); break; case ActionType.AddStaticItem: gameAction = new AddStaticItem(); break; case ActionType.AddStructure: gameAction = new AddStructure(); break; case ActionType.ChatMsg: gameAction = new ChatMsg(); break; case ActionType.Disconnect: gameAction = new Disconnect(); break; case ActionType.PickupBlockItem: gameAction = new PickupBlockItem(); break; case ActionType.PlayerInfo: gameAction = new PlayerInfo(); break; case ActionType.PlayerMove: gameAction = new PlayerMove(); break; case ActionType.PlayerOption: gameAction = new PlayerOption(); break; case ActionType.RemoveBlock: gameAction = new RemoveBlock(); break; case ActionType.RemoveBlockItem: gameAction = new RemoveBlockItem(); break; case ActionType.RemoveBlockMulti: gameAction = new RemoveBlockMulti(); break; case ActionType.ServerCommand: gameAction = new ServerCommand(); break; case ActionType.Connect: case ActionType.ServerMsg: case ActionType.ServerSync: case ActionType.GetWorld: throw new Exception(string.Format("Server should not receive action type: {0}", actionType)); case ActionType.Error: var bytes = 0; while (clientStream.ReadByte() != -1) { bytes++; } throw new Exception("GameAction 'Error' received. " + bytes + " byte(s) remained in the stream."); default: throw new Exception(string.Format("Unknown action type: {0}", actionType)); } gameAction.ConnectedPlayer = player; gameAction.Receive(); if (HasServerConsole && CaptureIncoming) //only stream messages if there is a console window and it has requested to display them { _serverConsole.UpdateStreamLogInvokable(gameAction, player, false); } if (actionType == ActionType.Disconnect) return; } } catch (Exception ex) { HandleNetworkError(player, ex); } }
public RemarkableEventData(ServerCommand cmd) { Command = cmd; }
/// <summary> /// Registers the command handler to react to certain server commands. /// </summary> public void RegisterCommandHandler(ServerCommand command, EventHandler<CommandEventArgs> handler) { if (EventsForCommand.ContainsKey(command)) { EventsForCommand[command].Handler += handler; } else { throw new NotImplementedException(); } }
public CommandInfo(ServerCommand id, short version) { _id = id; _version = version; }
/// <summary> /// Creates a new instance of the <see cref="UserCommandArgs"/> class. /// </summary> /// <param name="command">The code for the user command.</param> /// <param name="response">The code for the server's response.</param> /// <param name="buffer">Buffer containing the message from the server.</param> /// <param name="startIndex">Index into the buffer used to skip the header.</param> /// <param name="length">The length of the message in the buffer, including the header.</param> public UserCommandArgs(ServerCommand command, ServerResponse response, byte[] buffer, int startIndex, int length) { Command = command; Response = response; Buffer = buffer; StartIndex = startIndex; Length = length; }
private bool IsUserCommand(ServerCommand command) { ServerCommand[] userCommands = { ServerCommand.UserCommand00, ServerCommand.UserCommand01, ServerCommand.UserCommand02, ServerCommand.UserCommand03, ServerCommand.UserCommand04, ServerCommand.UserCommand05, ServerCommand.UserCommand06, ServerCommand.UserCommand07, ServerCommand.UserCommand08, ServerCommand.UserCommand09, ServerCommand.UserCommand10, ServerCommand.UserCommand11, ServerCommand.UserCommand12, ServerCommand.UserCommand13, ServerCommand.UserCommand14, ServerCommand.UserCommand15 }; return userCommands.Contains(command); }
/// <summary> /// Sends a server command to the publisher connection with associated <paramref name="message"/> data. /// </summary> /// <param name="commandCode"><see cref="ServerCommand"/> to send.</param> /// <param name="message">String based command data to send to server.</param> /// <returns><c>true</c> if <paramref name="commandCode"/> transmission was successful; otherwise <c>false</c>.</returns> public virtual bool SendServerCommand(ServerCommand commandCode, string message) { if (!string.IsNullOrWhiteSpace(message)) { using (BlockAllocatedMemoryStream buffer = new BlockAllocatedMemoryStream()) { byte[] bytes = m_encoding.GetBytes(message); buffer.Write(BigEndian.GetBytes(bytes.Length), 0, 4); buffer.Write(bytes, 0, bytes.Length); return SendServerCommand(commandCode, buffer.ToArray()); } } return SendServerCommand(commandCode); }
/// <summary> /// Raises the <see cref="ReceivedServerResponse"/> event. /// </summary> /// <param name="responseCode">Response received from the server.</param> /// <param name="commandCode">Command that the server responded to.</param> protected void OnReceivedServerResponse(ServerResponse responseCode, ServerCommand commandCode) { try { ReceivedServerResponse?.Invoke(this, new EventArgs<ServerResponse, ServerCommand>(responseCode, commandCode)); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(MessageLevel.Info, new InvalidOperationException($"Exception in consumer handler for ReceivedServerResponse event: {ex.Message}", ex), "ConsumerEventException"); } }
/// <summary> /// Raises the <see cref="ReceivedServerResponse"/> event. /// </summary> /// <param name="responseCode">Response received from the server.</param> /// <param name="commandCode">Command that the server responded to.</param> protected void OnReceivedServerResponse(ServerResponse responseCode, ServerCommand commandCode) { try { if ((object)ReceivedServerResponse != null) ReceivedServerResponse(this, new EventArgs<ServerResponse, ServerCommand>(responseCode, commandCode)); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(new InvalidOperationException($"Exception in consumer handler for ReceivedServerResponse event: {ex.Message}", ex)); } }
/// <summary> /// Raises the <see cref="ReceivedUserCommandResponse"/> event. /// </summary> /// <param name="command">The code for the user command.</param> /// <param name="response">The code for the server's response.</param> /// <param name="buffer">Buffer containing the message from the server.</param> /// <param name="startIndex">Index into the buffer used to skip the header.</param> /// <param name="length">The length of the message in the buffer, including the header.</param> protected void OnReceivedUserCommandResponse(ServerCommand command, ServerResponse response, byte[] buffer, int startIndex, int length) { try { UserCommandArgs args = new UserCommandArgs(command, response, buffer, startIndex, length); ReceivedUserCommandResponse?.Invoke(this, args); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(MessageLevel.Info, new InvalidOperationException($"Exception in consumer handler for UserCommandResponse event: {ex.Message}", ex), "ConsumerEventException"); } }
public static Command CreateServerCommand(Condition condition, ServerCommand serverCommand) { return new Command(condition, null, serverCommand, null, CommandType.Server, null, DataTransferOptions.None, ExecutionFrequency.FullUpdate60Hz); }
public MockCommand(ConnectionBase connection, ServerCommand id, short ver) : this(connection) { _id = id; _ver = ver; }
void GIVEN_second_testWorkflow() { var serverCommand = new ServerCommand { Command = ServerControlCommands.LoadConfiguraiton, Data = TestConstants.Workflow02 }; _browser.Put(UrlList.ServerControlPoint_absPath, with => { with.JsonBody<ServerCommand>(serverCommand); with.Accept("application/json"); }); }
public void handleCommand(ServerCommand servercommand) { string s = servercommand.command; ICommandListener icommandlistener = servercommand.commandListener; string s1 = icommandlistener.getUsername(); WorldServer worldserver = minecraftServer.worldMngr; ServerConfigurationManager serverconfigurationmanager = minecraftServer.configManager; if (s.ToLower().StartsWith("help") || s.ToLower().StartsWith("?")) { showHelp(icommandlistener); } else if (s.ToLower().StartsWith("list")) { icommandlistener.log( (new StringBuilder()).append("Connected players: ").append( serverconfigurationmanager.getPlayerList()).toString()); } else if (s.ToLower().StartsWith("stop")) { func_22115_a(s1, "Stopping the server.."); minecraftServer.initiateShutdown(); } else if (s.ToLower().StartsWith("save-all")) { func_22115_a(s1, "Forcing save.."); worldserver.saveWorld(true, null); func_22115_a(s1, "Save complete."); } else if (s.ToLower().StartsWith("save-off")) { func_22115_a(s1, "Disabling level saving.."); worldserver.levelSaving = true; } else if (s.ToLower().StartsWith("save-on")) { func_22115_a(s1, "Enabling level saving.."); worldserver.levelSaving = false; } else if (s.ToLower().StartsWith("op ")) { string s2 = s.Substring(s.IndexOf(" ")).Trim(); serverconfigurationmanager.opPlayer(s2); func_22115_a(s1, (new StringBuilder()).append("Opping ").append(s2).toString()); serverconfigurationmanager.sendChatMessageToPlayer(s2, "§eYou are now op!"); } else if (s.ToLower().StartsWith("deop ")) { string s3 = s.Substring(s.IndexOf(" ")).Trim(); serverconfigurationmanager.deopPlayer(s3); serverconfigurationmanager.sendChatMessageToPlayer(s3, "§eYou are no longer op!"); func_22115_a(s1, (new StringBuilder()).append("De-opping ").append(s3).toString()); } else if (s.ToLower().StartsWith("ban-ip ")) { string s4 = s.Substring(s.IndexOf(" ")).Trim(); serverconfigurationmanager.banIP(s4); func_22115_a(s1, (new StringBuilder()).append("Banning ip ").append(s4).toString()); } else if (s.ToLower().StartsWith("pardon-ip ")) { string s5 = s.Substring(s.IndexOf(" ")).Trim(); serverconfigurationmanager.pardonIP(s5); func_22115_a(s1, (new StringBuilder()).append("Pardoning ip ").append(s5).toString()); } else if (s.ToLower().StartsWith("ban ")) { string s6 = s.Substring(s.IndexOf(" ")).Trim(); serverconfigurationmanager.banPlayer(s6); func_22115_a(s1, (new StringBuilder()).append("Banning ").append(s6).toString()); EntityPlayerMP entityplayermp = serverconfigurationmanager.getPlayerEntity(s6); if (entityplayermp != null) { entityplayermp.playerNetServerHandler.kickPlayer("Banned by admin"); } } else if (s.ToLower().StartsWith("pardon ")) { string s7 = s.Substring(s.IndexOf(" ")).Trim(); serverconfigurationmanager.pardonPlayer(s7); func_22115_a(s1, (new StringBuilder()).append("Pardoning ").append(s7).toString()); } else if (s.ToLower().StartsWith("kick ")) { string s8 = s.Substring(s.IndexOf(" ")).Trim(); EntityPlayerMP entityplayermp1 = null; for (int i = 0; i < serverconfigurationmanager.playerEntities.size(); i++) { var entityplayermp5 = (EntityPlayerMP) serverconfigurationmanager.playerEntities.get(i); if (entityplayermp5.username.ToLowerInvariant() == s8.ToLowerInvariant()) { entityplayermp1 = entityplayermp5; } } if (entityplayermp1 != null) { entityplayermp1.playerNetServerHandler.kickPlayer("Kicked by admin"); func_22115_a(s1, (new StringBuilder()).append("Kicking ").append(entityplayermp1.username).toString()); } else { icommandlistener.log( (new StringBuilder()).append("Can't find user ").append(s8).append(". No kick.").toString()); } } else if (s.ToLower().StartsWith("tp ")) { string[] ask = s.Split(' '); if (ask.Length == 3) { EntityPlayerMP entityplayermp2 = serverconfigurationmanager.getPlayerEntity(ask[1]); EntityPlayerMP entityplayermp3 = serverconfigurationmanager.getPlayerEntity(ask[2]); if (entityplayermp2 == null) { icommandlistener.log( (new StringBuilder()).append("Can't find user ").append(ask[1]).append(". No tp.").toString()); } else if (entityplayermp3 == null) { icommandlistener.log( (new StringBuilder()).append("Can't find user ").append(ask[2]).append(". No tp.").toString()); } else { entityplayermp2.playerNetServerHandler.teleportTo(entityplayermp3.posX, entityplayermp3.posY, entityplayermp3.posZ, entityplayermp3.rotationYaw, entityplayermp3.rotationPitch); func_22115_a(s1, (new StringBuilder()).append("Teleporting ").append(ask[1]).append(" to ").append( ask[2]).append(".").toString()); } } else { icommandlistener.log("Syntax error, please provice a source and a target."); } } else if (s.ToLower().StartsWith("give ")) { string[] as1 = s.Split(' '); if (as1.Length != 3 && as1.Length != 4) { return; } string s9 = as1[1]; EntityPlayerMP entityplayermp4 = serverconfigurationmanager.getPlayerEntity(s9); if (entityplayermp4 != null) { try { int k = Integer.parseInt(as1[2]); if (Item.itemsList[k] != null) { func_22115_a(s1, (new StringBuilder()).append("Giving ").append(entityplayermp4.username).append (" some ").append(k).toString()); int l = 1; if (as1.Length > 3) { l = tryParse(as1[3], 1); } if (l < 1) { l = 1; } if (l > 64) { l = 64; } entityplayermp4.dropPlayerItem(new ItemStack(k, l, 0)); } else { icommandlistener.log( (new StringBuilder()).append("There's no item with id ").append(k).toString()); } } catch (NumberFormatException numberformatexception1) { icommandlistener.log( (new StringBuilder()).append("There's no item with id ").append(as1[2]).toString()); } } else { icommandlistener.log((new StringBuilder()).append("Can't find user ").append(s9).toString()); } } else if (s.ToLower().StartsWith("time ")) { string[] as2 = s.Split(' '); if (as2.Length != 3) { return; } string s10 = as2[1]; try { int j = Integer.parseInt(as2[2]); if ("add".Equals(s10, StringComparison.InvariantCultureIgnoreCase)) { worldserver.func_22076_a(worldserver.getWorldTime() + j); func_22115_a(s1, (new StringBuilder()).append("Added ").append(j).append(" to time").toString()); } else if ("set".Equals(s10, StringComparison.InvariantCultureIgnoreCase)) { worldserver.func_22076_a(j); func_22115_a(s1, (new StringBuilder()).append("Set time to ").append(j).toString()); } else { icommandlistener.log("Unknown method, use either \"add\" or \"set\""); } } catch (NumberFormatException numberformatexception) { icommandlistener.log( (new StringBuilder()).append("Unable to convert time value, ").append(as2[2]).toString()); } } else if (s.ToLower().StartsWith("say ")) { s = s.Substring(s.IndexOf(" ")).Trim(); minecraftLogger.info((new StringBuilder()).append("[").append(s1).append("] ").append(s).toString()); serverconfigurationmanager.sendPacketToAllPlayers( new Packet3Chat((new StringBuilder()).append("§d[Server] ").append(s).toString())); } else if (s.ToLower().StartsWith("tell ")) { string[] as3 = s.Split(' '); if (as3.Length >= 3) { s = s.Substring(s.IndexOf(" ")).Trim(); s = s.Substring(s.IndexOf(" ")).Trim(); minecraftLogger.info( (new StringBuilder()).append("[").append(s1).append("->").append(as3[1]).append("] ").append(s). toString()); s = (new StringBuilder()).append("§7").append(s1).append(" whispers ").append(s).toString(); minecraftLogger.info(s); if (!serverconfigurationmanager.sendPacketToPlayer(as3[1], new Packet3Chat(s))) { icommandlistener.log("There's no player by that name online."); } } } else if (s.ToLower().StartsWith("whitelist ")) { func_22113_a(s1, s, icommandlistener); } else { minecraftLogger.info("Unknown console command. Type \"help\" for help."); } }
internal ServerCommandEventArgs(ServerCommand cmd, Dictionary<string, string> args) { Command = cmd; Arguments = args; }
void GivenSendingServerCommand(ServerCommand serverCommand) { WhenSendingServerCommandAsXml(serverCommand); }