Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.InteropServices;
- public class WebSocket : MonoBehaviour {
- #region WebSocketJSLib Implement
- Queue<string> recvList = new Queue<string> (); //keep receive messages
- [DllImport("__Internal")]
- private static extern void Hello(); //test javascript plugin
- [DllImport("__Internal")]
- private static extern void InitWebSocket(string url); //create websocket connection
- [DllImport("__Internal")]
- private static extern int State(); //check websocket state
- [DllImport("__Internal")]
- private static extern void Send(string message); //send message
- [DllImport("__Internal")]
- private static extern void Close(); //close websocket connection
- //For Receive Message, this function was call by plugin, we need to keep this name.
- void RecvString(string message){
- recvList.Enqueue (message); //We will put the new message to the recvList queue.
- }
- //For Receive Message, this function was call by plugin, we need to keep this name.
- void ErrorString(string message){
- //We can do the same as RecvString here.
- }
- #endregion
- void Start () {
- Hello (); //We start with testing plugin
- StartCoroutine("RecvEvent"); //Then run the receive message loop
- }
- //Receive message loop function
- IEnumerator RecvEvent(){
- int j = 0;
- InitWebSocket ("ws://echo.websocket.org/"); //First we create the connection.
- while (true) {
- if (recvList.Count > 0) { //When our message queue has string coming.
- Dispatch(recvList.Dequeue()); //We will dequeue message and send to Dispatch function.
- }
- yield return null;
- }
- }
- //You can implement your game method here :)
- void Dispatch(string msg) {
- string[] splits = msg.Split(' ') ;
- switch (splits[0]) {
- case "turn" :
- //DO SOMETHING
- Debug.LogWarning("Turn "+splits[1]);
- break;
- default :
- Debug.Log("Distpatch : "+msg);
- break;
- }
- }
- //For UI, we defined it here
- void OnGUI() {
- if (GUI.Button(new Rect(10, 10, 150, 30), "Helllo,World"))
- Send("Helllo, World");
- if (GUI.Button(new Rect(10, 60, 150, 30), "Turn Right"))
- Send("turn r");
- if (GUI.Button(new Rect(10, 110, 150, 30), "Turn Left"))
- Send("turn l");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement