/// <summary>Process the operation get ws binding token described by response.</summary> /// <param name="context"> [in,out] The context.</param> /// <param name="response"> [in,out] The response.</param> /// <param name="previousComponent">The previous component.</param> internal static void ProcessOperationGetWsBindingToken( ref HttpContext context, ref HttpResponseMessage response, string previousComponent) { List <string> ids = new List <string>(); if (previousComponent != "Subscription") { ids.Add(previousComponent); } else { try { using (TextReader reader = new StreamReader(context.Request.Body)) { string requestContent = reader.ReadToEndAsync().Result; Parameters opParams = _fhirParser.Parse <Parameters>(requestContent); foreach (Parameters.ParameterComponent param in opParams.Parameter) { if (param.Name == "ids") { ids.Add((param.Value as Id).ToString()); } } } } catch (Exception ex) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent("Caught exception: " + ex.Message); return; } } foreach (string id in ids) { if (!SubscriptionManagerR4.Exists(id)) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent($"Invalid subscription id: {id}"); return; } } SubscriptionWsBindingToken token = SubscriptionWsBindingToken.GetTokenR4(ids); WebsocketManager.RegisterToken(token); Parameters parameters = new Parameters(); parameters.Add("token", new FhirString(token.Token.ToString())); parameters.Add("expiration", new FhirDateTime(new DateTimeOffset(token.ExpiresAt))); parameters.Add("subscriptions", new FhirString(string.Join(',', ids))); ProcessorUtils.SerializeR4(ref response, parameters); }
/// <summary>Main entry-point for this application.</summary> /// <param name="args">An array of command-line argument strings.</param> public static void Main(string[] args) { // setup our configuration (command line > environment > appsettings.json) Configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); // update configuration to make sure listen url is properly formatted Regex regex = new Regex(_regexBaseUrlMatch); Match match = regex.Match(Configuration["Client_Internal_Url"]); Configuration["Client_Internal_Url"] = match.ToString(); // initialize managers ClientManager.Init(); EndpointManager.Init(); WebsocketManager.Init(); // create our service host CreateHostBuilder(args).Build().StartAsync(); // create our web host CreateWebHostBuilder(args).Build().Run(); }
private void CheckAndSendHeartbeats(object state) { long currentTicks = DateTime.Now.Ticks; string heartbeatTime = string.Format(CultureInfo.InvariantCulture, "{0:o}", DateTime.Now.ToUniversalTime()); WebsocketManager.ProcessKeepalives(currentTicks, heartbeatTime); }
public void Start() { instance = this; // TODO Look into state usage on server side // Creating Teardown because GameFlowData checks if it isn't the current state, and null == null AppState_GameTeardown.Create(); Log.Info("Starting Server..."); UIFrontendLoadingScreen.Get().StartDisplayError("Starting Server..."); NetworkServer.useWebSockets = true; NetworkServer.Listen(Port); // Regiser Network Handlers GameMessageManager.RegisterAllHandlers(); // Load map bundle AssetBundle MapsBundle = AssetBundle.LoadFromFile(Path.Combine(Application.dataPath, @"Bundles\scenes\maps.bundle")); GameObject artemisServerObject = new GameObject("ArtemisServerComponent"); artemisServerComponent = artemisServerObject.AddComponent <ArtemisServerComponent>(); GameObject.DontDestroyOnLoad(artemisServerObject); WebsocketManager.Init(); ClientGamePrefabInstantiatorFix(); }
public void handle(string jsonString, WebsocketManager ws) { JToken token = JToken.Parse(jsonString); var messageType = token["type"]; Debug.WriteLine($"received {messageType.ToString()} message"); switch (messageType.ToString()) { case "associate_id": { var playerId = token["data"].ToObject <PlayerId>(); ws.AssociateId(playerId); return; } case "create_player": { var playerData = token["data"].ToObject <PlayerData>(); ws.CreatePlayer(playerData); return; } case "move_player": { var playerMove = token["data"].ToObject <PlayerMove>(); ws.MovePlayer(playerMove); return; } } }
public async Task DispatchAsync(WebsocketManager manager) { WebSocket socket = await manager.AcceptWebSocketAsync(); Task t1 = Task.Run(async() => await this.sender.SendAsync(socket)); Task t2 = Task.Run(async() => await this.receiver.ReceiveAsync(socket)); await Task.WhenAll(t1, t2); }
public override async Task OnConnected(WebSocket socket) { await base.OnConnected(socket); var socketId = WebsocketManager.GetId(socket); Log.Information("{socketId} is now connected", socketId); }
/// <summary>Write client messages.</summary> /// <param name="webSocket"> The web socket.</param> /// <param name="clientGuid"> Unique identifier for the client.</param> /// <param name="cancelToken">A token that allows processing to be canceled.</param> /// <returns>An asynchronous result.</returns> private async Task WriteClientMessages( WebSocket webSocket, Guid clientGuid, CancellationToken cancelToken) { // get the client object if (!WebsocketManager.TryGetClient(clientGuid, out WebsocketClientInformation client)) { // nothing to do here (will cancel on exit) return; } // loop until cancelled while (!cancelToken.IsCancellationRequested) { // do not bubble errors here try { // **** check for a message *** if (!client.MessageQ.TryDequeue(out string message)) { // wait and prevent exceptions await Task.Delay(_sendSleepDelayMs, cancelToken) .ContinueWith(_ => Task.CompletedTask); // go to next loop continue; } // grab a byte buffer of our data byte[] buffer = Encoding.UTF8.GetBytes(message); // send this message await webSocket.SendAsync( buffer, WebSocketMessageType.Text, true, cancelToken).ConfigureAwait(false); WebsocketManager.UpdateTimeoutForSentMessage(clientGuid); } // keep looping catch (Exception ex) { Console.WriteLine($"SubscriptionWebsocketHandler.WriteClientMessages" + $" <<< client: {clientGuid} caught exception: {ex.Message}"); // this socket is borked, exit break; } } }
void SubmitForm() { #if !UNITY_WEBGL || UNITY_EDITOR string username = usernameInput.text; string password = passwordInput.text; GameObject go = GameObject.Find("WebsocketManager"); WebsocketManager wsMan = (WebsocketManager)go.GetComponent(typeof(WebsocketManager)); Debug.Log(wsMan); wsMan.SendLoginRequest(username, password); #endif }
/// <summary>Main entry-point for this application.</summary> /// <param name="args">An array of command-line argument strings.</param> public static void Main(string[] args) { // setup our configuration (command line > environment > appsettings.json) Configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true) .AddEnvironmentVariables() .Build() ; // update configuration to make sure listen url is properly formatted Regex regex = new Regex(_regexBaseUrlMatch); Match match = regex.Match(Configuration["Server_Public_Url"]); Configuration["Server_Public_Url"] = match.ToString(); PublicUrl = match.ToString(); match = regex.Match(Configuration["Server_Internal_Url"]); Configuration["Server_Internal_Url"] = match.ToString(); // update external urls to make sure the DO have trailing slashes if (!Configuration["Server_FHIR_Url_R4"].EndsWith('/')) { Configuration["Server_FHIR_Url_R4"] = Configuration["Server_FHIR_Url_R4"] + '/'; } FhirServerUrlR4 = Configuration["Server_FHIR_Url_R4"]; // update external urls to make sure the DO have trailing slashes if (!Configuration["Server_FHIR_Url_R5"].EndsWith('/')) { Configuration["Server_FHIR_Url_R5"] = Configuration["Server_FHIR_Url_R5"] + '/'; } FhirServerUrlR5 = Configuration["Server_FHIR_Url_R5"]; // create our REST client RestClient = new HttpClient(); // initialize managers SubscriptionTopicManager.Init(); SubscriptionManagerR4.Init(); SubscriptionManagerR5.Init(); WebsocketManager.Init(); // create our service host CreateHostBuilder(args).Build().StartAsync(); // create our web host CreateWebHostBuilder(args).Build().Run(); }
/// <summary>Keepalive thread function.</summary> private void KeepaliveThreadFunc() { List <Guid> clientsToRemove = new List <Guid>(); try { // loop while there are clients while (!_clientMessageTimeoutDict.IsEmpty) { long currentTicks = DateTime.Now.Ticks; string keepaliveTime = string.Format(CultureInfo.InvariantCulture, "{0:o}", DateTime.Now.ToUniversalTime()); // traverse the dictionary looking for clients we need to send messages to foreach (KeyValuePair <Guid, long> kvp in _clientMessageTimeoutDict) { // check timeout if (currentTicks > kvp.Value) { // enqueue a message for this client if (WebsocketManager.TryGetClient(kvp.Key, out WebsocketClientInformation client)) { // enqueue a keepalive message client.MessageQ.Enqueue($"keepalive {keepaliveTime}"); } else { // client is gone, stop sending (cannot remove inside iterator) clientsToRemove.Add(kvp.Key); } } } // remove any clients we need to remove foreach (Guid clientGuid in clientsToRemove) { _clientMessageTimeoutDict.TryRemove(clientGuid, out _); } clientsToRemove.Clear(); Thread.Sleep(1000); } } catch (Exception ex) { Console.WriteLine($"SubscriptionWebsocketHandler.KeepaliveThreadFunc <<< exception: {ex.Message}"); } }
/// <summary>Tests queueing messages.</summary> /// <param name="clientGuid">Unique identifier for the client.</param> private void TestQueueingMessages(Guid clientGuid) { bool done = false; long messageNumber = 0; while (!done) { // check for no client if (!WebsocketManager.TryGetClient(clientGuid, out WebsocketClientInformation client)) { // done done = true; continue; } // queue a message for this client client.MessageQ.Enqueue($"Test message: {messageNumber++}, {DateTime.Now}"); // wait a couple of seconds Thread.Sleep(2000); } }
private void Initializer() { //_clientsList = new Hashtable(); //_sessionsList = new Hashtable(); _websocketManager = new WebsocketManager(); }
public async void ConnectButton_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(LoginPage.websocketUrl.Text)) { await DisplayAlert("Validation Error", "Server URL is required", "Re-try"); } else { tmr = new Timer(); tmr.Interval = 30000; // 10 second tmr.Elapsed += timerHandler; // We'll write it in a bit tmr.Start(); //if (nws == null) //{ nws = new WebsocketManager (); System.Diagnostics.Debug.WriteLine ("1111111111111111"); //} LoginPage.loginButton.IsEnabled = false; LoginPage.ConnectButton.IsEnabled = false; LoginPage.activityIndicator.IsRunning = true; try { System.Diagnostics.Debug.WriteLine ("2222222222222222222222"); WebsocketManager.websocketMaster.Open (); } catch { System.Diagnostics.Debug.WriteLine ("33333333333333333333"); tmr.Stop (); //tmr.Dispose (); LoginPage.activityIndicator.IsRunning = false; LoginPage.ConnectButton.IsEnabled = true; } } }
private void Awake() { activeManager = this; }
/// <summary>Reads client messages.</summary> /// <param name="webSocket"> The web socket.</param> /// <param name="clientGuid"> Unique identifier for the client.</param> /// <param name="cancelToken">A token that allows processing to be cancelled.</param> /// <returns>An asynchronous result.</returns> private async Task ReadClientMessages( WebSocket webSocket, Guid clientGuid, CancellationToken cancelToken) { // get the client object if (!WebsocketManager.TryGetClient(clientGuid, out WebsocketClientInformation client)) { // nothing to do here (will cancel on exit) return; } // create our receive buffer byte[] buffer = new byte[_messageBufferSize]; int count; int messageLength = 0; WebSocketReceiveResult result; // loop until cancelled while (!cancelToken.IsCancellationRequested) { // reset buffer offset messageLength = 0; // do not bubble errors here try { // read a message do { count = _messageBufferSize - messageLength; result = await webSocket.ReceiveAsync( new ArraySegment <byte>( buffer, messageLength, count), cancelToken).ConfigureAwait(false); messageLength += result.Count; }while (!result.EndOfMessage); // process this message if (result.MessageType == WebSocketMessageType.Close) { break; } // check for a bind request string message = Encoding.UTF8.GetString(buffer).Substring(0, messageLength); if (message.StartsWith("bind ", StringComparison.Ordinal)) { // grab the rest of the content message = message.Replace("bind ", string.Empty, StringComparison.Ordinal); string[] ids = message.Split(','); // traverse the requested ids foreach (string id in ids) { string subscriptionId = id.StartsWith("Subscription/", StringComparison.Ordinal) ? id.Replace("Subscription/", string.Empty, StringComparison.Ordinal) : id; // make sure this subscription exists if ((!SubscriptionManagerR4.Exists(subscriptionId)) && (!SubscriptionManagerR5.Exists(subscriptionId))) { continue; } // register this subscription to this client WebsocketManager.AddSubscriptionToClient(subscriptionId, clientGuid); } } if (message.StartsWith("bind-with-token ", StringComparison.Ordinal)) { // grab the rest of the content message = message.Replace("bind-with-token ", string.Empty, StringComparison.Ordinal); if (!Guid.TryParse(message, out Guid tokenGuid)) { continue; } // register this token to this client WebsocketManager.BindClientWithToken(tokenGuid, clientGuid); } if (message.StartsWith("unbind ", StringComparison.Ordinal)) { // grab the rest of the content message = message.Replace("unbind ", string.Empty, StringComparison.Ordinal); string[] ids = message.Split(','); // traverse the requested ids foreach (string id in ids) { string subscriptionId = id.StartsWith("Subscription/", StringComparison.Ordinal) ? id.Replace("Subscription/", string.Empty, StringComparison.Ordinal) : id; // remove this subscription from this client WebsocketManager.RemoveSubscriptionFromClient(subscriptionId, clientGuid); } } } // keep looping catch (Exception ex) { Console.WriteLine($"SubscriptionWebsocketHandler.ReadClientMessages" + $" <<< client: {clientGuid} caught exception: {ex.Message}"); // this socket is borked, exit break; } } }
public void Init() { this.currentUser = null; this.gsManager = null; this.wsManager = null; }
/// <summary>Accept and process web socket.</summary> /// <param name="context">The context.</param> /// <param name="client"> The client.</param> /// <returns>An asynchronous result.</returns> private async Task AcceptAndProcessWebSocket( HttpContext context, WebsocketClientInformation client) { // prevent WebSocket errors from bubbling up try { // accept the connection using (var webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false)) { // register our client WebsocketManager.RegisterClient(client); // create a cancellation token source so we can cancel our read/write tasks CancellationTokenSource processCancelSource = new CancellationTokenSource(); // link our local close with the application lifetime close for simplicity CancellationToken cancelToken = CancellationTokenSource.CreateLinkedTokenSource( _applicationStopping, processCancelSource.Token).Token; Task[] webSocketTasks = new Task[2]; // create send task webSocketTasks[0] = Task.Run(async() => { try { await WriteClientMessages(webSocket, client.Uid, cancelToken).ConfigureAwait(false); } finally { // **** cancel read if write task has exited *** processCancelSource.Cancel(); } }); // create receive task webSocketTasks[1] = Task.Run(async() => { try { await ReadClientMessages(webSocket, client.Uid, cancelToken).ConfigureAwait(false); } finally { // cancel write if read task has exited processCancelSource.Cancel(); } }); // start tasks and wait for them to complete await Task.WhenAll(webSocketTasks).ConfigureAwait(false); // close our web socket (do not allow cancel) await webSocket.CloseAsync( WebSocketCloseStatus.EndpointUnavailable, "Connection closing", CancellationToken.None).ConfigureAwait(false); } } catch (WebSocketException wsEx) { // just log for now Console.WriteLine($" <<< caught exception: {wsEx.Message}"); } finally { WebsocketManager.UnregisterClient(client.Uid); } return; }
private void InitializeGame(Scene scene) { GameManager.Get().SetTeamInfo(TeamInfo); GameManager.Get().SetGameInfo(GameInfo); SpawnObject("ApplicationSingletonsNetId"); var gameSceneSingletons = SpawnObject("GameSceneSingletons"); gameSceneSingletons.SetActive(true); //var cameraMan = gameSceneSingletons.GetComponent<CameraManager>(); //if (cameraMan != null) //{ // GameObject.Destroy(cameraMan); //} //else //{ // Log.Info("CameraManager is null"); //} var SharedEffectBarrierManager = SpawnObject("SharedEffectBarrierManager"); var SharedActionBufferObject = SpawnObject("SharedActionBuffer"); SharedActionBuffer = SharedActionBufferObject.GetComponent <SharedActionBuffer>(); SharedActionBuffer.Networkm_actionPhase = ActionBufferPhase.Done; foreach (GameObject sceneObject in scene.GetRootGameObjects()) { if (sceneObject.GetComponent <NetworkIdentity>() != null && !sceneObject.activeSelf) { Log.Info($"Activating scene object '{sceneObject.name}'"); sceneObject.SetActive(true); NetworkServer.Spawn(sceneObject); } } GameFlowData.Get().gameState = GameState.SpawningPlayers; bool destroyVisualsLoader = false; if (destroyVisualsLoader) { GameObject visualsLoader = GameObject.Find("VisualsLoader"); if (visualsLoader != null) { Log.Info("Trying to destroy VisualsLoader"); GameObject.Destroy(visualsLoader); } } Log.Info("Board is " + Board.Get()); List <LobbyPlayerInfo> playerInfoList = GameManager.Get().TeamInfo.TeamPlayerInfo; IsMapLoaded = true; for (int i = 0; i < playerInfoList.Count; i++) { LobbyPlayerInfo playerInfo = playerInfoList[i]; AddCharacterActor(playerInfo); } GameFlowData.Get().Networkm_currentTurn = 0; GameFlowData.Get().gameState = GameState.StartingGame; // Show what objects are present in the current scene UnityUtils.DumpSceneObjects(); WebsocketManager.ReportGameReady(); // Not sure where exactly it is supposed to happen }
public void ReceiveManager(WebsocketManager wsManager) { this.wsManager = wsManager; }
// Use this for initialization void Start() { wsManager = null; }
private void Initializer() { _websocketManager = new WebsocketManager(); }