다음 두 가지 방법으로 WebGL에서 네트워킹을 사용할 수 있습니다.
Optionally, you can use WebSockets or WebRTC from JavaScript to implement your own networking. Note that you can’t use .NET networking classes, because JavaScript code doesn’t have direct access to IP Sockets to implement network connectivity.
Unity supports the UnityWebRequest class in WebGL. To implement the UnityWebRequest class, Unity uses the JavaScript Fetch API, which uses the browser to handle web requests. This imposes security restrictions on accessing cross-domain resources.
Unity 콘텐츠를 호스팅하는 서버가 아닌 다른 서버로 웹 요청을 전송하는 경우 전송 대상 서버에서 Unity 콘텐츠를 승인해야 합니다.
WebGL에서 크로스 도메인 웹 리소스에 액세스하려면 액세스 대상 서버가 CORS(Cross-Origin Resource Sharing)를 사용하여 크로스 도메인 웹 리소스를 승인해야 합니다.
If you try to access content using UnityWebRequest, and the remote server doesn’t have CORS set up or configured correctly, an error like the following appears in the browser console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myserver.com/. This can be fixed by moving the resource to the same domain or enabling CORS.
서버는 전송하는 http 리스폰스에 Access-Control 헤더를 추가해야 합니다. 그래야만 어느 웹 페이지가 웹 브라우저에서 해당 정보를 읽을 권한이 있는지 나타낼 수 있습니다.
Unity WebGL이 모든 출처의 웹 서버에 있는 리소스에 액세스할 수 있도록 허용하는 Access-Control 헤더를 추가하는 방법에 대한 데모는 다음 예제를 참조하십시오. 이 예제는 공통 요청 헤더를 포함하며, GET, POST 또는 OPTIONS 메서드를 허용합니다.
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers": "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Origin": "*",
Don’t use code that blocks a UnityWebRequest download, such as this:
while(!www.isDone) {}
You can’t block the thread to wait for a UnityWebRequest download to finish otherwise your application freezes. Because WebGL is single threaded, and the fetch
API in JavaScript is asynchronous, your download might not finish unless you return control to the browser. Instead, use a Coroutine and a yield statement to wait for the download to finish. For more information, see Examples of coroutines using UnityWebRequest.
Unity Multiplayer enables communication via the WebSockets protocol. See NetworkServer.useWebSockets.
WebGL doesn’t allow direct access to IP Sockets, but you can use WebSockets or WebRTC (the two most common networking protocols supported by browsers) to get around this. While WebSockets are widely supported, WebRTC allows peer-to-peer connections between browsers and unreliable connections. Unity doesn’t have a built-in API that allows you to use WebSockets or WebRTC, but you can use a JavaScript plugin to implement this. You can find plugins that implement WebSocket networking on the Unity Asset Store.