/// <summary> /// Runs this game mode client. /// </summary> /// <returns>true if shut down by the game mode, false otherwise.</returns> /// <exception cref="Exception">Thrown if a game mode is already running.</exception> public bool Run() { if (InternalStorage.RunningClient != null) { throw new Exception("A game mode is already running!"); } InternalStorage.RunningClient = this; // Prepare the syncronization context _syncronizationContext = new SampSharpSyncronizationContext(); _messagePump = _syncronizationContext.MessagePump; SynchronizationContext.SetSynchronizationContext(_syncronizationContext); // Initialize the game mode and start the main routine Initialize(); // Pump new tasks _messagePump.Pump(); // Clean up InternalStorage.RunningClient = null; CommunicationClient.Disconnect(); return(_shuttingDown); }
public void Login(ModuleInfo userInfo) { if (FindClientByName(userInfo.Name) != null) { throw new NameInUseException("The name '" + userInfo.Name + "' is being used by another user. Please select another one."); } var client = CurrentClient; var clientProxy = client.GetClientProxy <ICommunicationClient>(); var chatClient = new CommunicationClient(client, clientProxy, userInfo); _clients[client.ClientId] = chatClient; client.Disconnected += Client_Disconnected; Task.Factory.StartNew( () => { OnModuleListChanged(); SendModuleListToClients(chatClient); SendUserLoginInfoToAllClients(userInfo); }); }
public async Task DownloadVerificationTestItems(int level) { if (!CommunicationClient.IsConnected) { await CommunicationClient.Connect(); } if (Instrument.CompositionType == CorrectorType.PTZ) { await DownloadTemperatureTestItems(level); await DownloadPressureTestItems(level); } if (Instrument.CompositionType == CorrectorType.T) { await DownloadTemperatureTestItems(level); } if (Instrument.CompositionType == CorrectorType.P) { await DownloadPressureTestItems(level); } await CommunicationClient.Disconnect(); }
/// <summary> /// Constructor. /// </summary> /// <param name="settingModel">Settings model.</param> /// <param name="communicationClient">Communication client.</param> public MultiPlayerModel(ISettingsModel settingModel, CommunicationClient communicationClient) { //Initializes variables. int port = settingModel.Port; string ip = settingModel.IpAddress; string serverMessage; this.CommunicationClient = communicationClient; this.CommunicationClient.ConnectionFailed += HandleConnectionFailed; //Sets property changed delegate. this.CommunicationClient.PropertyChanged += delegate(Object sender, PropertyChangedEventArgs e) { serverMessage = communicationClient.CommandFromUser; if (!string.IsNullOrEmpty(serverMessage) && !IsSingleCommand) { HandleServerResult(serverMessage); } else if (serverMessage != null) { ServerResponse = serverMessage; } }; }
public static async Task <bool> ValidateLogin(Server server, CommunicationClient client) { var email = ConversionHandler.ConvertBytesToString(await client.StreamCommunication.ReadAsync(User.UserEmailLength)); var password = ConversionHandler.ConvertBytesToString(await client.StreamCommunication.ReadAsync(User.UserPasswordLength)); var user = new UserDto() { Email = email, Password = password }; var existUser = await server.Service.AutenticateUserAsync(user); if (!existUser) { ProtocolHelpers.SendResponseCommand(ProtocolConstants.ResponseCommands.Error, client.StreamCommunication); client.StreamCommunication.Write(ConversionHandler.ConvertStringToBytes("Invalid User", ProtocolConstants.ResponseMessageLength)); } else { client.User = new User() { Email = email, Password = password }; loggerService.SendMessages("Login Successfully, mail: " + email); ProtocolHelpers.SendResponseCommand(ProtocolConstants.ResponseCommands.Ok, client.StreamCommunication); client.StreamCommunication.Write(ConversionHandler.ConvertStringToBytes("Login Successfully", ProtocolConstants.ResponseMessageLength)); } return(existUser); }
private async Task GetData(CommunicationClient client) { var logged = false; while (!logged) { var request = ConversionHandler.ConvertBytesToShort(await client.StreamCommunication.ReadAsync(ProtocolConstants.ShortTypeLength)); var commandType = ConversionHandler.ConvertBytesToShort(await client.StreamCommunication.ReadAsync(ProtocolConstants.ShortTypeLength)); if (commandType == (short)ProtocolConstants.RequestCommands.LOGIN) { logged = await ClientHandler.ValidateLogin(this, client); } else { logged = await ClientHandler.HandleCreateUser(this, client); } } var gettingData = true; while (gettingData) { await ProcessCommands(client); } }
private async Task NetworkingRoutine() { try { while (_running) { var data = await CommunicationClient.ReceiveAsync(); if (!_running) { return; } _commandWaitQueue.Release(data); } } catch (StreamCommunicationClientClosedException) { CoreLog.Log(CoreLogLevel.Warning, "Network routine ended because the communication with the SA:MP server was closed."); } catch (Exception e) { CoreLog.Log(CoreLogLevel.Error, "Network routine died! " + e); } }
/// <summary> /// Requests the game list. /// </summary> public void RequestList() { string command; //Parse into the right format. command = CommandParser.ParseToListCommand(); CommandPropertyChanged = "list"; //Send command to the server. try { CommunicationClient.SendToServer(command); while (string.IsNullOrEmpty(ServerResponse)) { continue; } HandleServerResult(ServerResponse); } catch (ArgumentNullException) { this.ConnectionLost?.Invoke(this, null); } }
/// <inheritdoc /> public bool Run() { if (InternalStorage.RunningClient != null) { throw new Exception("A game mode is already running!"); } InternalStorage.RunningClient = this; // Prepare the synchronization context var queue = new SemaphoreMessageQueue(); _synchronizationContext = new SampSharpSynchronizationContext(queue); _messagePump = new MessagePump(queue); SynchronizationContext.SetSynchronizationContext(_synchronizationContext); // Initialize the game mode and start the main routine Initialize(); // Pump new tasks _messagePump.Pump(e => OnUnhandledException(new UnhandledExceptionEventArgs("async", e))); // Clean up InternalStorage.RunningClient = null; CommunicationClient.Disconnect(); return(_shuttingDown); }
public static async Task HandleUploadPhoto(Server server, CommunicationClient client) { var name = ConversionHandler.ConvertBytesToString(await client.StreamCommunication.ReadAsync(Photo.PhotoNameLength)); var extension = ConversionHandler.ConvertBytesToString(await client.StreamCommunication.ReadAsync(Photo.PhotoExtensionLength)); var fileSize = ConversionHandler.ConvertBytesToLong(await client.StreamCommunication.ReadAsync(ProtocolConstants.LongTypeLength)); if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(extension)) { ProtocolHelpers.SendMessageCommand(ProtocolConstants.ResponseCommands.Ok, client, "Input Error"); } var photo = new PhotoDto() { Name = name, Extension = extension, FileSize = fileSize, UserEmail = client.User.Email }; await server.Service.UploadPhotoAsync(photo); var fileName = $"{PhotosPath}\\Image_{photo.Id}{extension}"; await FileHandler.ReceiveFileWithStreams(fileSize, fileName, client.StreamCommunication); loggerService.SendMessages("Image uploaded"); ProtocolHelpers.SendMessageCommand(ProtocolConstants.ResponseCommands.Ok, client, "Added succesfully"); }
public Lobby(bool UseOnline) { DicAllRoom = new Dictionary<string, RoomInformations>(); ArrayLobbyPlayer = new BattleMapPlayer[0]; ArrayLobbyFriends = new BattleMapPlayer[0]; if (UseOnline) { Dictionary<string, OnlineScript> DicOnlineGameClientScripts = new Dictionary<string, OnlineScript>(); Dictionary<string, OnlineScript> DicOnlineCommunicationClientScripts = new Dictionary<string, OnlineScript>(); OnlineGameClient = new BattleMapOnlineClient(DicOnlineGameClientScripts); OnlineCommunicationClient = new CommunicationClient(DicOnlineCommunicationClientScripts); DicOnlineGameClientScripts.Add(ConnectionSuccessScriptClient.ScriptName, new ConnectionSuccessScriptClient()); DicOnlineGameClientScripts.Add(RedirectScriptClient.ScriptName, new RedirectScriptClient(OnlineGameClient)); DicOnlineGameClientScripts.Add(LoginSuccessScriptClient.ScriptName, new LoginSuccessScriptClient(this)); DicOnlineGameClientScripts.Add(RoomListScriptClient.ScriptName, new RoomListScriptClient(this)); DicOnlineGameClientScripts.Add(JoinRoomLocalScriptClient.ScriptName, new JoinRoomLocalScriptClient(OnlineGameClient, OnlineCommunicationClient, this, false)); DicOnlineGameClientScripts.Add(JoinRoomFailedScriptClient.ScriptName, new JoinRoomFailedScriptClient(OnlineGameClient, this)); DicOnlineGameClientScripts.Add(ServerIsReadyScriptClient.ScriptName, new ServerIsReadyScriptClient()); DicOnlineCommunicationClientScripts.Add(ReceiveGlobalMessageScriptClient.ScriptName, new ReceiveGlobalMessageScriptClient(OnlineCommunicationClient)); DicOnlineCommunicationClientScripts.Add(ReceiveGroupMessageScriptClient.ScriptName, new ReceiveGroupMessageScriptClient(OnlineCommunicationClient)); DicOnlineCommunicationClientScripts.Add(ReceiveGroupInviteScriptClient.ScriptName, new ReceiveGroupInviteScriptClient(OnlineCommunicationClient)); DicOnlineCommunicationClientScripts.Add(ReceiveRemoteGroupInviteScriptClient.ScriptName, new ReceiveRemoteGroupInviteScriptClient(OnlineCommunicationClient)); DicOnlineCommunicationClientScripts.Add(MessageListGroupScriptClient.ScriptName, new MessageListGroupScriptClient(OnlineCommunicationClient)); DicOnlineCommunicationClientScripts.Add(PlayerListScriptClient.ScriptName, new PlayerListScriptClient(OnlineCommunicationClient, this)); DicOnlineCommunicationClientScripts.Add(FriendListScriptClient.ScriptName, new FriendListScriptClient(OnlineCommunicationClient, this)); } }
public static async Task HandleViewCommentsPhoto(FileServer.Server server, CommunicationClient client) { var photoIdParsed = ConversionHandler.ConvertBytesToLong(await client.StreamCommunication.ReadAsync(ProtocolConstants.LongTypeLength)); ProtocolHelpers.SendResponseCommand(ProtocolConstants.ResponseCommands.ListComments, client.StreamCommunication); var photo = new PhotoDto() { Id = photoIdParsed }; var comments = await server.Service.GetCommentsAsync(photo); var length = comments.Count() * (User.UserEmailLength + User.UserNameLength + Comment.CommentLength); var data = ConversionHandler.ConvertIntToBytes(length); client.StreamCommunication.Write(data); comments.ToList().ForEach((elem) => { var comment = new Comment() { Message = elem.Message, Commentator = new User() { Email = elem.UserEmail, Name = elem.UserName } }; ProtocolHelpers.SendCommentData(client.StreamCommunication, comment); }); loggerService.SendMessages("Comments listed correctly"); }
public static async Task HandleViewPhotos(Server server, CommunicationClient client) { ProtocolHelpers.SendResponseCommand(ProtocolConstants.ResponseCommands.ListPhotos, client.StreamCommunication); var photos = await server.Service.GetPhotosAsync(); var length = photos.Count() * (User.UserEmailLength + ProtocolConstants.LongTypeLength + Photo.PhotoNameLength + Photo.PhotoExtensionLength + ProtocolConstants.LongTypeLength); var data = ConversionHandler.ConvertIntToBytes(length); client.StreamCommunication.Write(data); photos.ForEach((elem) => { var photo = new Photo() { Id = elem.Id, Name = elem.Name, Extension = elem.Extension, FileSize = elem.FileSize, User = new User() { Email = elem.UserEmail } }; ProtocolHelpers.SendPhotoData(client.StreamCommunication, photo); }); loggerService.SendMessages("Images listed correctly"); }
/// <summary> /// Joins the game. /// </summary> /// <param name="gameName">Game name.</param> public void JoinGame(string gameName) { string command; //Parse into the right format. command = CommandParser.ParseToJoinCommand(gameName); IsSingleCommand = true; //Send command to the server. try { CommunicationClient.SendToServer(command); while (string.IsNullOrEmpty(ServerResponse)) { continue; } HandleMazeCommand(ServerResponse); } catch (ArgumentNullException) { this.ConnectionLost?.Invoke(this, null); } }
private async void Initialize() { _mainThread = Thread.CurrentThread.ManagedThreadId; CoreLog.Log(CoreLogLevel.Initialisation, "SampSharp GameMode Client"); CoreLog.Log(CoreLogLevel.Initialisation, "-------------------------"); CoreLog.Log(CoreLogLevel.Initialisation, $"v{CoreVersion.Version.ToString(3)}, (C)2014-2020 Tim Potze"); CoreLog.Log(CoreLogLevel.Initialisation, "Multi-process run mode is active. FOR DEVELOPMENT PURPOSES ONLY!"); CoreLog.Log(CoreLogLevel.Initialisation, "Run your server in hosted run mode for production environments. See https://sampsharp.net/running-in-production for more information."); CoreLog.Log(CoreLogLevel.Initialisation, ""); AppDomain.CurrentDomain.ProcessExit += (sender, args) => { CoreLog.Log(CoreLogLevel.Info, "Shutdown signal received"); ShutDown(); if (_mainRoutine != null && !_mainRoutine.IsCompleted) { _mainRoutine.Wait(); } if (_networkingRoutine != null && !_networkingRoutine.IsCompleted) { _networkingRoutine.Wait(); } }; CoreLog.Log(CoreLogLevel.Info, $"Connecting to the server via {CommunicationClient}..."); await CommunicationClient.Connect(); _running = true; CoreLog.Log(CoreLogLevel.Info, "Set up networking routine..."); StartNetworkingRoutine(); CoreLog.Log(CoreLogLevel.Info, "Connected! Waiting for server announcement..."); ServerCommandData data; do { data = await _commandWaitQueue.WaitAsync(); // Could receive ticks if reconnecting. } while (data.Command == ServerCommand.Tick); if (!VerifyVersionData(data)) { return; } CoreLog.Log(CoreLogLevel.Info, "Initializing game mode provider..."); _gameModeProvider.Initialize(this); CoreLog.Log(CoreLogLevel.Info, "Sending start signal to server..."); Send(ServerCommand.Start, new[] { (byte)_startBehaviour }); CoreLog.Log(CoreLogLevel.Info, "Set up main routine..."); _mainRoutine = MainRoutine(); }
protected override Task <CommunicationClient <IBookFastBookingAPI> > CreateClientAsync(string endpoint, CancellationToken cancellationToken) { var client = new CommunicationClient <IBookFastBookingAPI>(() => { return(apiClientFactory.CreateApiClientAsync(new Uri(endpoint))); }); return(Task.FromResult(client)); }
public CreateRoomScreen(BattleMapOnlineClient OnlineClient, CommunicationClient OnlineCommunicationClient, string RoomType) { this.OnlineGameClient = OnlineClient; this.OnlineCommunicationClient = OnlineCommunicationClient; this.RoomType = RoomType; RoomSubtype = "Deathmatch"; MinNumberOfPlayer = 1; MaxNumberOfPlayer = 8; }
public async Task DownloadPressureTestItems(int level) { var test = Instrument.VerificationTests.FirstOrDefault(x => x.TestNumber == level).PressureTest; if (test != null) { test.Items = await CommunicationClient.GetItemValues(CommunicationClient.ItemDetails.PressureItems()); } }
public CreateRoomBattle(TripleThunderOnlineClient OnlineClient, CommunicationClient OnlineCommunicationClient, string RoomType) { this.OnlineGameClient = OnlineClient; this.OnlineCommunicationClient = OnlineCommunicationClient; this.RoomType = RoomType; RoomSubtype = "Deathmatch"; MinNumberOfPlayer = 2; MaxNumberOfPlayer = 8; }
public JoinRoomLocalScriptClient(BattleMapOnlineClient OnlineGameClient, CommunicationClient OnlineCommunicationClient, GameScreen ScreenOwner, bool RemoveOwner = false) : base(ScriptName) { this.OnlineGameClient = OnlineGameClient; this.OnlineCommunicationClient = OnlineCommunicationClient; this.ScreenOwner = ScreenOwner; this.RemoveOwner = RemoveOwner; HasGame = false; ListJoiningPlayerID = new List <string>(); }
private void SendModuleListToClients(CommunicationClient client) { var moduleList = ModuleList.Where(user => user.Name != client.User.Name).ToArray(); if (moduleList.Length <= 0) { return; } client.ClientProxy.GetUserList(moduleList); }
private void btn_newClient_Click(object sender, EventArgs e) { IPAddress IP; if (!IPAddress.TryParse(tb_Ip1.Text, out IP)) { MessageBox.Show("IP illegal"); } Client = new CommunicationClient(tb_Ip1.Text, Int32.Parse(tx_PortName.Text)); //Receive Thread Task.Run(() => receiveFromServer()); }
public BattleSelect(TripleThunderOnlineClient OnlineGameClient, CommunicationClient OnlineCommunicationClient, BattleRoomInformations Room) { this.OnlineGameClient = OnlineGameClient; this.OnlineCommunicationClient = OnlineCommunicationClient; this.Room = Room; if (Room.ListRoomPlayer.Count == 0) { PlayerManager.ListLocalPlayer[0].PlayerType = Player.PlayerTypeHost; Room.AddLocalPlayer(PlayerManager.ListLocalPlayer[0]); } }
private async Task DisconnectUserAsync(CommunicationClient client) { if (client.User != null) { var user = new UserDto() { Email = client.User.Email }; await Service.LogoutUser(user); } }
protected override Task <CommunicationClient <IBookFastBookingAPI> > CreateClientAsync(string endpoint, CancellationToken cancellationToken) { var client = new CommunicationClient <IBookFastBookingAPI>(async() => { var accessToken = await accessTokenProvider.AcquireTokenAsync(); var credentials = string.IsNullOrEmpty(accessToken) ? (ServiceClientCredentials) new EmptyCredentials() : new TokenCredentials(accessToken); return(new BookFastBookingAPI(new Uri(endpoint), credentials)); }); return(Task.FromResult(client)); }
private async Task Connection(CommunicationClient client) { try { await GetData(client); } catch (Exception) { await DisconnectUserAsync(client); client.ClientListener.Close(); } }
protected override Task <CommunicationClient <IBookFastFilesAPI> > CreateClientAsync(string endpoint, CancellationToken cancellationToken) { // clients that maintain persistent connections to a service should // create that connection here. // an HTTP client doesn't maintain a persistent connection. var client = new CommunicationClient <IBookFastFilesAPI>(() => { return(apiClientFactory.CreateApiClientAsync(new Uri(endpoint))); }); return(Task.FromResult(client)); }
public SendRoomIDScriptClient(TripleThunderOnlineClient OnlineGameClient, CommunicationClient OnlineCommunicationClient, GameScreen ScreenOwner, string RoomName, string RoomType, string RoomSubtype, byte MinNumberOfPlayer, byte MaxNumberOfPlayer) : base(ScriptName) { this.OnlineGameClient = OnlineGameClient; this.OnlineCommunicationClient = OnlineCommunicationClient; this.ScreenOwner = ScreenOwner; this.RoomName = RoomName; this.RoomType = RoomType; this.RoomSubtype = RoomSubtype; this.MinNumberOfPlayer = MinNumberOfPlayer; this.MaxNumberOfPlayer = MaxNumberOfPlayer; }
public void RequestRegisterToServer() { this.communicationClient = new CommunicationClient(this.communicationView.ipEndPoint,this.communicationView.ListeningPort); this.communicationClient.RecieveMsgEvent += this.communicationView.ResponseRecieveMsg; this.communicationClient.RecieveFileEvent += this.communicationView.ResponseRecieveFile; this.communicationClient.EndRecieveFileEvent += this.communicationView.ResponseEndRecieveFile; this.communicationClient.OnRecievedControlImageEvent += this.communicationView.OnResponseRecievedControlImage; this.communicationClient.OnRecievedControlCommandEvent += this.communicationView.OnResponseRecievedControlCommand; this.communicationClient.Register(this.communicationView.SenderName,new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"),this.communicationView.ListeningPort)); }
public MissionSelect(TripleThunderOnlineClient OnlineGameClient, CommunicationClient OnlineCommunicationClient, MissionRoomInformations Room) { IsHost = true; this.OnlineGameClient = OnlineGameClient; this.OnlineCommunicationClient = OnlineCommunicationClient; this.Room = Room; ListMissionInfo = new List <MissionInfo>(); if (Room.ListRoomPlayer.Count == 0) { PlayerManager.ListLocalPlayer[0].PlayerType = Player.PlayerTypeHost; Room.AddLocalPlayer(PlayerManager.ListLocalPlayer[0]); } }
/// <inheritdoc /> public void ShutDown() { if (_shuttingDown || !_running) { return; } CommunicationClient.Send(ServerCommand.Disconnect, null); // Give the server time to receive the reconnect signal. Thread.Sleep(100); _shuttingDown = true; _commandWaitQueue.Release(new ServerCommandData(ServerCommand.Nop, new byte[0])); }