Advertisement
Guest User

Untitled

a guest
Sep 5th, 2015
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Runtime.InteropServices;
  5.  
  6. public class WebSocket : MonoBehaviour {
  7.  
  8. #region WebSocketJSLib Implement
  9. Queue<string> recvList = new Queue<string> (); //keep receive messages
  10.  
  11. [DllImport("__Internal")]
  12. private static extern void Hello(); //test javascript plugin
  13.  
  14. [DllImport("__Internal")]
  15. private static extern void InitWebSocket(string url); //create websocket connection
  16.  
  17. [DllImport("__Internal")]
  18. private static extern int State(); //check websocket state
  19.  
  20. [DllImport("__Internal")]
  21. private static extern void Send(string message); //send message
  22.  
  23. [DllImport("__Internal")]
  24. private static extern void Close(); //close websocket connection
  25.  
  26. //For Receive Message, this function was call by plugin, we need to keep this name.
  27. void RecvString(string message){
  28. recvList.Enqueue (message); //We will put the new message to the recvList queue.
  29. }
  30.  
  31. //For Receive Message, this function was call by plugin, we need to keep this name.
  32. void ErrorString(string message){
  33. //We can do the same as RecvString here.
  34. }
  35. #endregion
  36.  
  37. void Start () {
  38. Hello (); //We start with testing plugin
  39. StartCoroutine("RecvEvent"); //Then run the receive message loop
  40. }
  41.  
  42. //Receive message loop function
  43. IEnumerator RecvEvent(){
  44. int j = 0;
  45. InitWebSocket ("ws://echo.websocket.org/"); //First we create the connection.
  46. while (true) {
  47. if (recvList.Count > 0) { //When our message queue has string coming.
  48. Dispatch(recvList.Dequeue()); //We will dequeue message and send to Dispatch function.
  49. }
  50. yield return null;
  51. }
  52. }
  53.  
  54. //You can implement your game method here :)
  55. void Dispatch(string msg) {
  56. string[] splits = msg.Split(' ') ;
  57. switch (splits[0]) {
  58. case "turn" :
  59. //DO SOMETHING
  60. Debug.LogWarning("Turn "+splits[1]);
  61. break;
  62. default :
  63. Debug.Log("Distpatch : "+msg);
  64. break;
  65. }
  66. }
  67.  
  68. //For UI, we defined it here
  69. void OnGUI() {
  70. if (GUI.Button(new Rect(10, 10, 150, 30), "Helllo,World"))
  71. Send("Helllo, World");
  72.  
  73. if (GUI.Button(new Rect(10, 60, 150, 30), "Turn Right"))
  74. Send("turn r");
  75.  
  76. if (GUI.Button(new Rect(10, 110, 150, 30), "Turn Left"))
  77. Send("turn l");
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement