WWW サーバにアクセスしてデータを取得する例。
Webサーバは、localhost上 tomcat (8080番ポート)上のサーブレット /proj/NetData 「データのupload, download」 を想定している。
WebGet.cs |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class WebGet : MonoBehaviour { // Start is called before the first frame update void Start() { StartCoroutine(GetText()); } // Update is called once per frame void Update() { StartCoroutine(GetText()); } IEnumerator GetText() { UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/proj/NetData"); yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { // get data as a text. Debug.Log(www.downloadHandler.text); // get as a binary data. //byte[] results = www.downloadHandler.data; } } } |
localhost 上の tomcat サーバにアクセスして、データが存在すれば、テキストとして入手する。
変更した WebGet.cs |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using System; public class WebGet : MonoBehaviour { // Start is called before the first frame update void Start() { StartCoroutine(GetText()); } // Update is called once per frame void Update() { StartCoroutine(GetText()); } IEnumerator GetText() { UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/proj/NetData"); yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { // get data as a text. //Debug.Log(www.downloadHandler.text); string s = www.downloadHandler.text; string[] words = s.Split(' '); int n = Int32.Parse(words[0]); if (n != 0) Debug.Log(s); // get as a binary data. //byte[] results = www.downloadHandler.data; } } } |