Skip to content

Instantly share code, notes, and snippets.

@msciotti
Created March 16, 2018 22:15
Show Gist options
  • Save msciotti/9ead5be9c27f9ae7e8624e3de6e843f2 to your computer and use it in GitHub Desktop.
Save msciotti/9ead5be9c27f9ae7e8624e3de6e843f2 to your computer and use it in GitHub Desktop.
Unity RPC Connection
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using System.Text;
using System;
using System.Threading.Tasks;
using System.Net.WebSockets;
using System.IO;
[System.Serializable]
public class RuntheDiscordThing : MonoBehaviour {
async public void OnReady(System.UInt16 port, System.UIntPtr context)
{
Debug.Log("Discord: Running on port" + port);
ClientWebSocket ws = new ClientWebSocket();
ws.Options.SetRequestHeader("Origin", "https://localhost");
await ws.ConnectAsync(new Uri("ws://127.0.0.1:" + port + "/?v=1&client_id=YOUR_ID&encoding=json"), System.Threading.CancellationToken.None);
Debug.Log("WS should be open: " + ws.State);
await Task.WhenAll(Send(ws), Receive(ws));
}
public void OnError(System.UInt32 code, [MarshalAs(UnmanagedType.LPStr)] System.String message, System.UIntPtr context)
{
Debug.Log("Discord: Error " + code + "| " + message);
}
void OnEnable()
{
Debug.Log("Discord: Start");
GameBridge.SetReadyCallback(OnReady, UIntPtr.Zero);
GameBridge.SetErrorCallback(OnError, UIntPtr.Zero);
Debug.Log("Discord: Called init");
GameBridge.Initialize("YOUR_CLIENT_ID", "Assets/");
Debug.Log("Discord: Set callbacks");
}
private static async Task Send(ClientWebSocket ws)
{
while (ws.State == WebSocketState.Open)
{
var json = "{\"nonce\":\"1234\",\"args\":{\"client_id\":\"YOUR_CLIENT_ID\",\"scopes\":[\"rpc\"]},\"cmd\":\"AUTHORIZE\"}";
byte[] buffer = Encoding.UTF8.GetBytes(json);
Debug.Log("Sending message: " + json);
await ws.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, System.Threading.CancellationToken.None);
await Task.Delay(5000);
}
}
private static async Task Receive(ClientWebSocket ws)
{
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);
WebSocketReceiveResult result = null;
using (var ms = new MemoryStream())
{
do
{
result = await ws.ReceiveAsync(buffer, System.Threading.CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
var text = reader.ReadToEnd();
Debug.Log("Got message: " + text);
}
}
else if(result.MessageType == WebSocketMessageType.Close)
{
Debug.Log("Socket closed");
}
else
{
var text = Encoding.UTF8.GetString(buffer.Array, 0, buffer.Count);
Debug.Log("Got response: " + text);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment