Last active
June 23, 2019 20:34
-
-
Save alvivar/7f6f756d93fe7342425fb2f6881eb0f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using BestHTTP.WebSocket; | |
using UnityEngine; | |
public class ControllerClient : MonoBehaviour | |
{ | |
private WebSocket webSocket; | |
public class Query | |
{ | |
public int id; | |
public string type; | |
public string query; | |
} | |
void Start() | |
{ | |
// webSocket = new WebSocket(new Uri("ws://127.0.0.1:4000/"), "", "-H Sec-Websocket-Protocol: graphql-ws"); | |
// This one works ^ | |
webSocket = new WebSocket(new Uri("wss://us1.prisma.sh/andres-v/hello-world/dev"), "", "-H Sec-Websocket-Protocol: graphql-ws"); | |
// This doesn't work, the websocket doesn't even open | |
webSocket.OnOpen += OnWebSocketOpen; | |
webSocket.OnError += OnWebSocketError; | |
webSocket.OnMessage += OnWebSocketMessage; | |
webSocket.Open(); | |
Debug.Log($"Socket Open() at {Time.time}"); | |
} | |
private void OnWebSocketOpen(WebSocket webSocket) | |
{ | |
Debug.Log($"WebSocket Open! {webSocket.State}"); | |
var query = new Query(); | |
query.type = "init"; | |
var jsonData = JsonUtility.ToJson(query); | |
Debug.Log($"{jsonData} at {Time.time}"); | |
webSocket.Send(jsonData); | |
} | |
private void OnWebSocketError(WebSocket webSocket, Exception ex) | |
{ | |
Debug.Log("WebSocket Error!"); | |
error += ex.TargetSite; | |
// Debug.Log($"{ex.Message} at {Time.time}"); | |
} | |
private void OnWebSocketMessage(WebSocket webSocket, string message) | |
{ | |
Debug.Log($"WebSocket message: {message} at {Time.time}"); | |
var response = JsonUtility.FromJson<Query>(message); | |
if (response.type == "init_success") | |
{ | |
var subQuery = new Query(); | |
subQuery.id = 1; | |
subQuery.type = "subscription_start"; | |
subQuery.query = "subscription { messages { id content created } }"; | |
var jsonData = JsonUtility.ToJson(subQuery); | |
Debug.Log($"{jsonData} at {Time.time}"); | |
webSocket.Send(jsonData); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment