Comment se connecter à la firebase database depuis Unity

J’essaie de me connecter à une firebase database MS SQL via Unity. Cependant, lorsque j’essaie d’ouvrir une connexion, je reçois une exception IOException: Connection lost.

J’ai importé System.Data.dll depuis Unity \ Editor \ Data \ Mono \ lib \ mono \ 2.0. J’utilise le code suivant:

using UnityEngine; using System.Collections; using System.Data.Sql; using System.Data.SqlClient; public class SQL_Controller : MonoBehaviour { ssortingng conSsortingng = "Server=myaddress.com,port;" + "Database=databasename;" + "User ID=username;" + "Password=password;"; public ssortingng GetSsortingngFromSQL() { LoadConfig(); ssortingng result = ""; SqlConnection connection = new SqlConnection(conSsortingng); connection.Open(); Debug.Log(connection.State); SqlCommand Command = connection.CreateCommand(); Command.CommandText = "select * from Artykuly2"; SqlDataReader ThisReader = Command.ExecuteReader(); while (ThisReader.Read()) { result = ThisReader.GetSsortingng(0); } ThisReader.Close(); connection.Close(); return result; } } 

C’est l’erreur que j’ai:

 IOException: Connection lost Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader () Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket () Mono.Data.Tds.Protocol.TdsComm.GetByte () Mono.Data.Tds.Protocol.Tds.ProcessSubPacket () Mono.Data.Tds.Protocol.Tds.NextResult () Mono.Data.Tds.Protocol.Tds.SkipToEnd () Rethrow as TdsInternalException: Server closed the connection. Mono.Data.Tds.Protocol.Tds.SkipToEnd () Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters) Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters) 

S’il vous plaît ne pas tenir compte des risques de sécurité avec cette approche, je dois le faire pour les tests, la sécurité viendra plus tard. Merci pour votre temps.

S’il vous plaît ne pas tenir compte des risques de sécurité avec cette approche

Ne le fais pas comme ça . Peu importe si la sécurité viendra avant ou après. Vous finirez par réécrire tout le code car le mot de passe est codé en dur dans votre application, ce qui permet de le décomstackr et de le récupérer facilement . Faites la connexion correctement maintenant afin de ne pas avoir à réécrire toute l’application.

Exécutez votre commande de firebase database sur votre serveur avec php, perl ou tout autre langage avec lequel vous êtes à l’aise, mais cela doit être fait sur le serveur.

Dans Unity, utilisez la classe WWW ou UnityWebRequest pour communiquer avec ce script, puis vous pourrez envoyer et recevoir des informations de Unity vers le serveur. Il y a beaucoup d’ exemples là- bas . Même avec ceci, vous devez encore implémenter votre propre sécurité mais c’est beaucoup mieux que ce que vous avez maintenant.

Vous pouvez également recevoir des données multiples avec json .

Voici un exemple complet de ce wiki Unity. Il montre comment interagir avec une firebase database dans Unity en utilisant php côté serveur et Unity + C # côté client.

Côté serveur :

Ajouter un score avec PDO :

 An error has ocurred.
', $e->getMessage() ,'

'; } $realHash = md5($_GET['name'] . $_GET['score'] . $secretKey); if($realHash == $hash) { $sth = $dbh->prepare('INSERT INTO scores VALUES (null, :name, :score)'); try { $sth->execute($_GET); } catch(Exception $e) { echo '

An error has ocurred.

', $e->getMessage() ,'

'; } } ?>

Récupérer le score avec PDO :

 An error has occurred.
', $e->getMessage() ,'

'; } $sth = $dbh->query('SELECT * FROM scores ORDER BY score DESC LIMIT 5'); $sth->setFetchMode(PDO::FETCH_ASSOC); $result = $sth->fetchAll(); if(count($result) > 0) { foreach($result as $r) { echo $r['name'], "\t", $r['score'], "\n"; } } ?>

Activer la stratégie interdomaine sur le serveur :

Ce fichier doit être nommé “crossdomain.xml” et placé à la racine de votre serveur Web. Unity exige que les sites Web auxquels vous souhaitez accéder via une requête WWW disposent d’une stratégie interdomaine.

     

Côté Client / Unité :

Le code client d’Unity se connecte au serveur, interagit avec PDO et ajoute ou récupère le score en fonction de la fonction appelée. Ce code client est légèrement modifié pour être compilé avec la dernière version d’Unity.

 private ssortingng secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server public ssortingng addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url public ssortingng highscoreURL = "http://localhost/unity_test/display.php"; //Text to display the result on public Text statusText; void Start() { StartCoroutine(GetScores()); } // remember to use StartCoroutine when calling this function! IEnumerator PostScores(ssortingng name, int score) { //This connects to a server side php script that will add the name and score to a MySQL DB. // Supply it with a ssortingng representing the players name and the players score. ssortingng hash = Md5Sum(name + score + secretKey); ssortingng post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash; // Post the URL to the site and create a download object to get the result. WWW hs_post = new WWW(post_url); yield return hs_post; // Wait until the download is done if (hs_post.error != null) { print("There was an error posting the high score: " + hs_post.error); } } // Get the scores from the MySQL DB to display in a GUIText. // remember to use StartCoroutine when calling this function! IEnumerator GetScores() { statusText.text = "Loading Scores"; WWW hs_get = new WWW(highscoreURL); yield return hs_get; if (hs_get.error != null) { print("There was an error getting the high score: " + hs_get.error); } else { statusText.text = hs_get.text; // this is a GUIText that will display the scores in game. } } public ssortingng Md5Sum(ssortingng strToEncrypt) { System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding(); byte[] bytes = ue.GetBytes(strToEncrypt); // encrypt bytes System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(bytes); // Convert the encrypted bytes back to a ssortingng (base 16) ssortingng hashSsortingng = ""; for (int i = 0; i < hashBytes.Length; i++) { hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); } return hashString.PadLeft(32, '0'); } 

Ceci est juste un exemple sur la façon de procéder correctement. Si vous devez implémenter une fonctionnalité de session et que vous vous souciez de la sécurité, consultez le protocole OAuth 2.0 . Il devrait y avoir des bibliothèques existantes qui aideront à démarrer avec le protocole OAuth .