CAn't connect to a local server (XAMPP) from HoloLens - c#

I'm trying to build a connection between the HoloLens and XAMMP server.
when i test the app on unity, it works fine but it doesn't work on the device.
Ps: you can access the server when writing the IP address of the server In Microsoft Edge.
Windows defender firewall is disabled
Network capabilities are checked (publishing settings)
XAMPP server is reconfigured to be accessible to all devices
what am I missing here ? how can I make this work ?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class test : MonoBehaviour
{
public Text playerDisplay;
public Text score;
public Button submit;
public InputField nameField;
public GameObject bb;
public Text Error;
public void CallLogIn()
{
StartCoroutine(Loginplayer());
}
IEnumerator Loginplayer()
{
WWWForm form = new WWWForm();
form.AddField("name", nameField.text);
WWW www = new WWW("http://192.168.1.100/sqlconnect/test.php", form);
yield return www;
if (www.text[0] == '0')
{
DBManager.username = nameField.text;
DBManager.score = int.Parse(www.text.Split('\t')[1]);
playerDisplay.text = "player: " + DBManager.username;
score.text = "score: " + DBManager.score;
bb.SetActive(true);
}
else
{
Error.text = "save failes. Error #" + www.error;
bb.SetActive(false);
}
DBManager.logedOut();
}
}

I encountered this kind of issue as well. I tried to connect the HoloLens to different entities (MySQL DB, OPCUA Server) but it always fails on the HoloLens (working fine in the editor). Searching on google only revealed similar problems from other people, but no solutions.
So my solution is to use the WWW class to receive data from a HTML-Webserver that hosts plain text. This server (I used nodejs and python) executes the query to the database depending on the GET-request it receives from the HoloLens.

Related

www request not completing on Android 9 (Pie) Unity3d

I have a simple script which creates a www request in game to check which country this apk running. It was working fine before android 9 OS devices but failed on android 9 OS devices. My www.error is giving an unknown error string.
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class GeoData : MonoBehaviour
{
private void Start()
{
StartCoroutine(GetText());
}
IEnumerator GetText()
{
UnityWebRequest www = UnityWebRequest.Get("http://ip-api.com/json");// I also changed www string but all in vein
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
//above Android 8 os devices, its comes here and debug "Unknow error"
Debug.Log("Done with Error: " + www.error);
}
else
{
Debug.Log("Final data is ="+ www.text);
string stringToSplit = www.text;
char[] splitters = { ',', ':', '"' };
string[] splittedString = stringToSplit.Split(splitters, System.StringSplitOptions.RemoveEmptyEntries);
foreach (var item in splittedString)
{
Debug.Log(item); // Country is at 6th index
}
}
}
}
Ok I have figured out what was the problem..
A non-secure URL, and it's now prohibited in Android 9 Pie.
you can't request.
so URL must be sure like this (https)

XAMPP becomes super slow after some time

Does anyone ever encounter the MYSQL in XAMPP being super slow after sometime?
I have a unity application that asking a string to be downloaded with this php script.
<?php
include 'Config.php'; // Just a normal mysqli connection setup
//the post from Unity.
$var_uniqueID = $_POST['uniqueID_Post'];
$conn = OpenCon(); // open connection
//create a query
$sql = "SELECT
var_name,
var_value
FROM variable_current_values
WHERE uniqueID = '".$var_uniqueID."' ";
$result = mysqli_query($conn, $sql);
if( mysqli_num_rows($result) > 0)
{
//show data for each row
while($row = mysqli_fetch_assoc($result))
{
echo "".$row['var_name'] .
"|".$row['var_value'] . "";
}
}
CloseCon($conn); // close the connection
?>
This PHP script is being called with c# script of UnityWebRequest
//www variable
private UnityWebRequest unityWebRequest;
void Update ()
{
if (unityWebRequest == null)
{
//fetch The data Widget
StartCoroutine(RealDataFetchWhere(this.name));
}
}
private IEnumerator RealDataFetchWhere(string _uniqueIDPost)
{
//gives the unique key
WWWForm fetchingForm = new WWWForm();
fetchingForm.AddField("uniqueID_Post", _uniqueIDPost);
//load and wait until the data is downloaded
unityWebRequest = UnityWebRequest.Post(**thePHPLink**, fetchingForm);
yield return unityWebRequest.SendWebRequest();
string data = unityWebRequest.downloadHandler.text;
print("the Data is : " + data);
}
At first everything seems to be fine. Data is downloaded perfectly(almost in realtime speed).
However after like more than 10 minutes, the XAMPP mySQL starting to slow down considerably. I try to modified the data manually in XAMPP and it takes about 5 - 8 seconds until the "row is affected"
If i leave them longer without closing my unity program, XAMPP start to freeze and disconnected.
Does anyone know the solutions to counter this problem ?

How to bypass NameServer IpAddress?

I am working in unity 2018. In My project I have to find my website address. I have used this code to find the web address.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
public class IpAddressFind : MonoBehaviour {
public string url="https://www.friendslearn.com";
void Start () {
GetIP(url);
}
public static string GetIP(string url) {
url = url.Replace("http://", ""); //remove http://
url = url.Replace("https://", ""); //remove https://
url = url.Substring(0, url.IndexOf("/")); //remove everything after the first /
try {
IPHostEntry hosts = Dns.GetHostEntry(url);
Debug.Log(hosts.AddressList.Length);
Debug.Log(hosts.HostName);
if(hosts.AddressList.Length > 0)
{
Debug.Log(hosts.AddressList[0].ToString());
Debug.Log("Final");
}
} catch {
Debug.Log ("Could not get IP for URL " + url);
}
return null;
}
}
This returns the CloudFlare address.
Actually my website is working in amazon EC2 and I am using nameserver in CloudFlare. When I run the code it returns the CloudFlare web address. Actually my web address is 13.37.202.259. But it returns CloudFlare's IP.
How to find my EC2 address?
EDIT:I am using old code. Is there any new API to find my IP address. In Unity 2018.

Unity - saving simple data off device [duplicate]

I am trying to connect to a MS SQL database through Unity. However, when I try to open a connection, I get an IOException: Connection lost.
I have imported System.Data.dll from Unity\Editor\Data\Mono\lib\mono\2.0. I am using the following code:
using UnityEngine;
using System.Collections;
using System.Data.Sql;
using System.Data.SqlClient;
public class SQL_Controller : MonoBehaviour {
string conString = "Server=myaddress.com,port;" +
"Database=databasename;" +
"User ID=username;" +
"Password=password;";
public string GetStringFromSQL()
{
LoadConfig();
string result = "";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
Debug.Log(connection.State);
SqlCommand Command = connection.CreateCommand();
Command.CommandText = "select * from Artykuly2";
SqlDataReader ThisReader = Command.ExecuteReader();
while (ThisReader.Read())
{
result = ThisReader.GetString(0);
}
ThisReader.Close();
connection.Close();
return result;
}
}
This is the error I get:
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)
Please disregard any security risks with this approach, I NEED to do this for testing, security will come later.
Thank you for your time.
Please disregard any security risks with this approach
Do not do it like this. It doesn't matter if security will come before or after. You will end of re-writing the whole code because the password is hard-coded in your application which can be decompiled and retrieved easily. Do the connection the correct way now so that you won't have to re-write the whole application.
Run your database command on your server with php, perl or whatever language you are comfortable with but this should be done on the server.
From Unity, use the WWW or UnityWebRequest class to communicate with that script and then, you will be able to send and receive information from Unity to the server. There are many examples out there. Even with this, you still need to implement your own security but this is much more better than what you have now.
You can also receive data multiple with json.
Below is a complete example from this Unity wiki. It shows how to interact with a database in Unity using php on the server side and Unity + C# on the client side.
Server Side:
Add score with PDO:
<?php
// Configuration
$hostname = 'localhot';
$username = 'yourusername';
$password = 'yourpassword';
$database = 'yourdatabase';
$secretKey = "mySecretKey"; // Change this value to match the value stored in the client javascript below
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$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 '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
}
?>
Retrieve score with PDO:
<?php
// Configuration
$hostname = 'localhost';
$username = 'yourusername';
$password = 'yourpassword';
$database = 'yourdatabase';
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has occurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$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";
}
}
?>
Enable cross domain policy on the server:
This file should be named "crossdomain.xml" and placed in the root of your web server. Unity requires that websites you want to access via a WWW Request have a cross domain policy.
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
Client/Unity Side:
The client code from Unity connects to the server, interacts with PDO and adds or retrieves score depending on which function is called. This client code is slightly modified to compile with the latest Unity version.
private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server
public string addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url
public string 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(string 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 string representing the players name and the players score.
string hash = Md5Sum(name + score + secretKey);
string 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 string Md5Sum(string 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 string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
This is just an example on how to properly do this. If you need to implement session feature and care about security, look into the OAuth 2.0 protocol. There should be existing libraries that will help get started with the OAuth protocol.
An alternative would be to create your own dedicated server in a command prompt to do your communication and connecting it to unity to Handel multiplayer and SQL communication. This way you can stick with it all being created in one language. But a pretty steep learning curve.
Unity is game engine.
so That's right what the answer says.
but, Some domains need to connect database directly.
You shouldn't do that access database directly in game domain.
Anyway, The problem is caused by NON-ENGLISH computer name.
I faced sort of following errors at before project.
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)
And after changing computer name as ENGLISH, It works.
I don't know how it's going. But It works.
Mono's System.Data.dll has some issues in P.C has NON-ENGLISH Computer name.
So, at least Unity project.
You should tell your customer Do not set their computer name as NON-ENGLISH.
I don't know people in mono knows these issue or not.
---------- It's OK in after 2018 version ----------
Api Compatibility Level > .Net 4.x
You can connect database in Non-english computer name machine.

How to stream/download&play an audio from URL?

I need to stream or download and play an audio getted from an URL in Unity3D, running on iOS.
The Audio comes from a text-to-audio service and I need to play it on Unity:
http://api.ispeech.org/api/rest?apikey=...&action=convert&voice=eurspanishfemale&text=hola+que+tal
I've been googling all the morning and not found a valid solution...
There is a code snippet in the Unity3D documentation (WWW-audioClip,WWW.GetAudioClip), but is not working, I have debugged and the error says it couldn't open the file.
using UnityEngine;
using System.Collections;
public class AudioURLScript : MonoBehaviour {
public string url = "http://api.ispeech.org/api/rest?apikey=...&action=convert&voice=eurspanishfemale&text=hola+que+tal";
public AudioSource source;
void Start() {
WWW www = new WWW("file://"+url);
source = GetComponent<AudioSource>();
source.clip = www.GetAudioClip(false,true);
}
void Update() {
if (!source.isPlaying && source.clip.isReadyToPlay)
source.Play();
}
}
Thanks
SOLUTION
This is my working solution right now.
void Start(){
StartCoroutine(DownloadAndPlay("http://api.ispeech.org/api/rest?apikey=...&action=convert&voice=eurspanishfemale&text=Hola+que+tal"));
}
IEnumerator DownloadAndPlay(string url)
{
WWW www = new WWW(url);
yield return www;
AudioSource audio = GetComponent<AudioSource>();
audio.clip = www.GetAudioClip(false, true,AudioType.MPEG);
audio.Play();
}
You don't mention the platform you are on, so I'm going to assume Windows.
Unity Windows runtime only supports WAV or OGG. The link to the audio service file you provided is downloading as a MP2 Audio File (common in broadcasting). Unity will not be able to play that (or MP3).
For reference, Android and iOS platforms do support MP3 (but not MP2).
So, you're first issue is to make sure your audio source is in compatible format.
The code sample is incorrect for 3 reasons;
the URL is https: (which tells unity to download from the internet) but then you pre-pend file: to it (which tells unity to load from the local file system). So you should pick one or the other.
it wouldn't work if you picked https because that particular link (I know it's just an example) but it requires a user to be logged in to the service (and using cookies to know that), so it doesn't send you an audio file, it sends you a HTML page telling the user to login or register.
As #fafase says, the WWW must be placed within a co-routine, so that it can download over multiple frames.
OK, here's what I suggest.
If you can know the audio files a head of time, download them and transcode to OGG (if windows) or MP3 (if mobile) and upload them to your own server (say Amazon S3, or a $10 a month unlimited website).
Then, use this code to download and play it:
StartCoroutine(DownloadAndPlay("http://myserver.com/audio/test.ogg"));
IEnumerator DownloadAndPlay(string url)
{
WWW www = new WWW(url);
yield return www;
AudioSource audio = GetComponent<AudioSource>();
audio.clip = www.GetAudioClip(false, false);
audio.Play();
}
A WWW object is a wrapper for a HTTP request, containing the creation of the connection, the transfer of the data and the closing of the connection (and some extra actions).
This does not happen in one frame and requires a coroutine.
void Start() {
StartCoroutine(GetAudio(url));
}
private IEnumerator GetAudio(string url)
{
WWW www = new WWW("file://"+url);
yield return www;
if(string.IsNullOrEmpty(www.error) == false)
{
Debug.Log("Did not work");
yield break;
}
source = GetComponent<AudioSource>();
source.clip = www.GetAudioClip(false,true);
}
The WWW package got deprecated and Unity3D recommended using the UnityWebRequest package for API communications.
Try the following code snippet to download audio from a URL and play it using the AudioSource gameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class DownloadAndPlay : MonoBehaviour
{
public AudioSource audioSource;
// Start is called before the first frame update
void Start()
{
string URL = "http://api.ispeech.org/api/rest?apikey=...&action=convert&voice=eurspanishfemale&text=hola+que+tal";
StartCoroutine(DownloadAudio(URL));
}
// Update is called once per frame
void Update()
{
}
IEnumerator DownloadAudio(string URL) {
using (UnityWebRequest www_audio = UnityWebRequestMultimedia.GetAudioClip(URL, AudioType.MPEG)) {
yield return www_audio.SendWebRequest();
if (www_audio.isNetworkError) {
Debug.Log(www_audio.error);
} else {
AudioClip clip = DownloadHandlerAudioClip.GetContent(www_audio);
audioSource.clip = clip;
audioSource.Play();
}
}
}
}
For more: https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html

Categories