RecvString() public method

public RecvString ( ) : string
return string
Ejemplo n.º 1
0
        public IEnumerator listenInvoice(string invoiceId, Action <Invoice> actionOnInvoice)
        {
            Debug.Log("listenInvoice(): websocket start : invoiceId=" + invoiceId);
            WebSocket w = new WebSocket(new Uri("ws://echo.websocket.org"));

            yield return(w.Connect());

            w.SendString("Hi there");
            int i = 0;

            while (true)
            {
                string reply = w.RecvString();
                if (reply != null)
                {
                    Debug.Log("Received: " + reply);
                    w.SendString("Hi there" + i++);
                }
                if (w.error != null)
                {
                    Debug.LogError("Error: " + w.error);
                    break;
                }
                yield return(0);
            }
            w.Close();
        }
Ejemplo n.º 2
0
    // Use this for initialization
    IEnumerator Start()
    {
        ws = new WebSocket(new System.Uri("ws://localhost:3000"));

        yield return(StartCoroutine(ws.Connect()));

        while (true)
        {
            string respuesta = ws.RecvString();

            if (ws.error != null)
            {
                Debug.LogError(ws.error);
                break;
            }

            if (respuesta != null)
            {
                Debug.Log("Servidor > " + respuesta);
                // Hay que buscar un objeto y en caso de no encontrarlo se crea con unos parámetros
            }
            yield return(0);
        }

        // Inaccesible pero más tarde los cambiamos, siempre se tiene que cerrar la conexión.
        ws.Close();
    }
Ejemplo n.º 3
0
    IEnumerator Start()
    {
        WebSocket w = new WebSocket(new Uri("ws://" + ip + ":" + port));

        yield return(StartCoroutine(w.Connect()));

        w.SendString("START");

        while (true)
        {
            if ((int)((Time.time % 60) * NetworkSpeed) >= x)
            {
                w.SendString("Open for: " + x.ToString());
                x++;
            }

            string reply = w.RecvString();
            if (reply != null)
            {
                Debug.Log(reply);
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }
            yield return(0);
        }
        w.Close();
    }
Ejemplo n.º 4
0
    /// <summary>
    /// Start the Birb Client.
    /// </summary>
    /// <returns>Nothing right now.</returns>
    IEnumerator Start()
    {
        gameStateManager = GetComponent<GameStateManager>();
        Uri server = new Uri("ws://birb.herokuapp.com");
        Uri localhost = new Uri("ws://localhost:5000");
        socket = new WebSocket(server);
        callbacks = new Dictionary<BirbMessageCode, Callback>();
        yield return StartCoroutine(socket.Connect());
        int i = 0;

        // Testing
        //RunUnitTests();

        while (true)
        {
            string reply = socket.RecvString();
            if (reply != null)
            {
                Debug.Log("Received: " + reply);
                Process(reply);
            }
            if (socket.Error != null)
            {
                Debug.LogError("Error: " + socket.Error);
                break;
            }
            yield return 0;
        }
        socket.Close();
    }
Ejemplo n.º 5
0
    // Use this for initialization
    IEnumerator Start()
    {
        WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:1337"));

        yield return(StartCoroutine(w.Connect()));

        w.SendString("Hi there");
        int i = 0;

        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                Debug.Log("Received: " + reply);
                w.SendString("Hi there" + i++);
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }
            yield return(0);
        }
        w.Close();
    }
Ejemplo n.º 6
0
	// Use this for initialization
	IEnumerator Start () {
		WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:8080/websocket"));
		yield return StartCoroutine(w.Connect());

		int i = 0;
		w.SendString(PackMessage("Hi there", i));
		while (true)
		{
			string reply = w.RecvString();
			if (reply != null)
			{
				Message msg = UnpackMessage (reply);
				Debug.Log ("Received: " + msg.msg + ", " + msg.no);
				w.SendString (PackMessage ("Hi there", i));
			}
			if (w.error != null)
			{
				Debug.LogError ("Error: " + w.error);
				break;
			}

			++i;

			yield return 0;
		}
		w.Close();
	}
    IEnumerator WebSocketCoroutine()
    {
        string uri = addressInputField.text + "/" + channelInputField.text + "?name=" + nameInputField.text;

        statusView.NotConnected();
        webSocket = new WebSocket(new Uri(uri));
        statusView.Connect();
        yield return(StartCoroutine(webSocket.Connect()));

        statusView.Connected();
        while (true)
        {
            string reply = webSocket.RecvString();
            if (reply != null)
            {
                textAreaView.RecvString(reply);
            }
            if (webSocket.error != null)
            {
                textAreaView.RecvString(reply);
                break;
            }
            yield return(new WaitForSeconds(1f));
        }
    }
Ejemplo n.º 8
0
    IEnumerator Start()
    {
        position = transform.position;
        if (!SettingStat.IsNormal)
        {
            //Debug.Log(SettingStat.ServerURL);
            String URL = "ws://" + SettingStat.ServerURL;
            w = new WebSocket(new Uri(URL));
            yield return(StartCoroutine(w.Connect()));

            w.SendString("User Unity");

            while (true)
            {
                //Debug.Log("got here");
                order = w.RecvString();
                //Debug.Log(order);
                if (order != null)
                {
                    // Debug.Log("Received order: " + order);
                }
                if (w.error != null)
                {
                    // Debug.LogError("Error: " + w.error);
                    break;
                }

                yield return(0);
            }
        }
    }
Ejemplo n.º 9
0
    // Use this for initialization
    IEnumerator Start()
    {
        webSocketConn = new WebSocket(new Uri("ws://" + playsemIpPortAddress + "/playsemserenderer"));
        yield return(StartCoroutine(webSocketConn.Connect()));

        webSocketConn.SendString("{\"setSem\":[{\"sensoryEffectMetadata\":\"" + metadata + "\", \"duration\":\"60000\"}]}");

        while (true)
        {
            string reply = webSocketConn.RecvString();
            if (reply != null)
            {
                Debug.Log("Received: " + reply);
                if (reply.Contains("SemPrepared") && reply.Contains("true"))
                {
                    yield return(StartCoroutine(prepareVideo()));

                    webSocketConn.SendString("{\"setPlay\":[{\"currentTime\":\"0\"}]}");
                    yield return(StartCoroutine(playVideo()));
                }
            }
            if (webSocketConn.error != null)
            {
                Debug.LogError("Error: " + webSocketConn.error);
                break;
            }
            yield return(0);
        }
        webSocketConn.Close();
    }
Ejemplo n.º 10
0
        public IEnumerator WaitMessage()
        {
            string recv;

            while ((recv = webSocket.RecvString()) == null)
            {
                yield return(null);
            }
            Data = recv;
        }
Ejemplo n.º 11
0
    IEnumerator Start()
    {
        // Connect to Ros (websocket) server
        WebSocket w = new WebSocket(new Uri("ws://10.1.10.14:9013/"));

        yield return(StartCoroutine(w.Connect()));

        GameObject A1go = GameObject.Find("agilus_A1_GEO_stream");
        GameObject A2go = GameObject.Find("agilus_A2_GEO_stream");
        GameObject A3go = GameObject.Find("agilus_A3_GEO_stream");
        GameObject A4go = GameObject.Find("agilus_A4_GEO_stream");
        GameObject A5go = GameObject.Find("agilus_A5_GEO_stream");
        GameObject A6go = GameObject.Find("agilus_A6_GEO_stream");

        // Listen for ROS data on websocket
        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                //Debug.Log ("Received Joints: "+reply);
                JointClass joints = JsonUtility.FromJson <JointClass>(reply);
                //Debug.Log ("A1: "+ joints.position[0]);

                float degA1 = joints.position [0] * Mathf.Rad2Deg;
                float degA2 = -joints.position[1] * Mathf.Rad2Deg;
                float degA3 = -joints.position[2] * Mathf.Rad2Deg;
                float degA4 = -joints.position[3] * Mathf.Rad2Deg;
                float degA5 = -joints.position[4] * Mathf.Rad2Deg;
                float degA6 = -joints.position[5] * Mathf.Rad2Deg;

                Vector3 tempA1 = new Vector3(0f, 0f, degA1);
                Vector3 tempA2 = new Vector3(0f, degA2, 0f);
                Vector3 tempA3 = new Vector3(0f, degA3, 0f);
                Vector3 tempA4 = new Vector3(degA4, 0f, 0f);
                Vector3 tempA5 = new Vector3(0f, degA5, 0f);
                Vector3 tempA6 = new Vector3(degA6, 0f, 0f);

                A1go.transform.localEulerAngles = tempA1;
                A2go.transform.localEulerAngles = tempA2;
                A3go.transform.localEulerAngles = tempA3;
                A4go.transform.localEulerAngles = tempA4;
                A5go.transform.localEulerAngles = tempA5;
                A6go.transform.localEulerAngles = tempA6;
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }
            yield return(0);
        }
        w.Close();
    }
Ejemplo n.º 12
0
    IEnumerator Start()
    {
        w = new WebSocket(new Uri(url));
        yield return(StartCoroutine(w.Connect()));

        // mark game connection with "game", will use second number for player id,
        // third for selecting which sprite to use
        w.SendString("gameInit_na_na");

        while (open)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                moveData = JsonConvert.DeserializeObject <MoveData>(reply);
                if (players.Any(obj => obj.name == moveData.id))
                {
                    //the player exists
                    var currentPlayer = players.SingleOrDefault(obj => obj.name == moveData.id);

                    //if socket was closed, remove player
                    if (moveData.position == "close")
                    {
                        currentPlayer.SetActive(false);
                    }
                    //else move player as specified
                    else
                    {
                        currentPlayer.GetComponent <PlayerController>()
                        .Move(StringToVector3(moveData.position));
                    }
                }
                else if (moveData.position == "START")
                {
                    //instantiating the player
                    var newPlayer = Instantiate(player,
                                                new Vector3(Random.Range(-28.0f, 28.0f), Random.Range(-14.0f, 14.0f), 0),
                                                Quaternion.identity);
                    //renaming them
                    newPlayer.name = moveData.id;
                    newPlayer.GetComponent <PlayerController>().AttachSprite(moveData.sprite);
                    players.Add(newPlayer);
                }
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }

            yield return(0);
        }
        w.Close();
    }
Ejemplo n.º 13
0
    private IEnumerator OpenConnectionToServer()
    {
        w = new WebSocket(new Uri("ws://localhost:3000/ws"));

        yield return(StartCoroutine(w.Connect()));

        w.SendString("{\"type\":\"CONNECTED\"}");
        stateManager.ChangeConnectionState(ConnectionState.CONNECTED);

        while (true)
        {
            string reply = w.RecvString();



            ServerMessage message = JsonUtility.FromJson <ServerMessage>(reply);
            if (reply != null)
            {
                if (message.type == "LoginRequest")
                {
                    DispatchMessage(JsonUtility.FromJson <LoginRequestMessage> (reply));
                }
                if (message.type == "LoginSuccessful")
                {
                    DispatchMessage(JsonUtility.FromJson <LoginRequestMessage> (reply));
                }

                if (message.type == "RequestCharacterResponse")
                {
                    DispatchMessage(JsonUtility.FromJson <RequestCharacterResponse> (reply));
                    RequestCharacterResponse characters = JsonUtility.FromJson <RequestCharacterResponse> (reply);

                    for (int i = 0; i < characters.payload.characters.Length; i++)
                    {
                        Debug.Log(characters.payload.characters[i].name);
                        Debug.Log(characters.payload.characters[i].ownerid);
                        Debug.Log(characters.payload.characters[i].position.x);
                        Debug.Log(characters.payload.characters[i].position.y);
                        Debug.Log(characters.payload.characters[i].mapid);
                        Debug.Log(characters.payload.characters[i].spriteid);
                    }
                }
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                wsopen = false;
                stateManager.ChangeConnectionState(ConnectionState.DISCONNECTED);
                break;
            }
            yield return(0);
        }
        w.Close();
    }
Ejemplo n.º 14
0
    // ----------------------------------------------------------------------
    // サーバーからの要求を受け取る処理.
    // ----------------------------------------------------------------------
    private void RecieveInfo()
    {
        string jsonString = ws.RecvString();

        while (jsonString != null)
        {
            SocketDataListWrapper recieveDataListWrapper = JsonUtility.FromJson <SocketDataListWrapper>(jsonString);
            switch (recieveDataListWrapper.eventName)
            {
            case "login":
                SocketData recieveData = JsonUtility.FromJson <SocketData>(jsonString);
                LoginCallback(recieveData);
                break;

            case "sendHostInfo":
                SetPlayerInfo(recieveDataListWrapper);
                break;
            }
            jsonString = ws.RecvString();
        }
        //Debug.Log(jsonString);
    }
Ejemplo n.º 15
0
        IEnumerator Start()
        {
            for (;;)
            {
#if (UNITY_EDITOR || !UNITY_WEBGL) && !WEBSOCKET_BROWSER_DEBUG
                ws_ = new WebSocket(new Uri(websocketServerUrl));
                yield return(StartCoroutine(ws_.Connect()));
#else
                if (!ws_)
                {
                    ws_ = GetComponent <WebSocketBrowser>() ?? gameObject.AddComponent <WebSocketBrowser>();
                    Application.ExternalEval("init();");
                }
#endif
                isConnected_ = true;

                for (;;)
                {
                    var message = ws_.RecvString();
                    while (message != null)
                    {
                        if (Application.isPlaying)
                        {
                            OnReceive(message);
                        }
                        message = ws_.RecvString();
                    }
                    if (ws_.Error != null)
                    {
                        LogError(ws_.Error);
                        isConnected_ = false;
                        yield return(new WaitForSeconds(1));

                        break;
                    }
                    yield return(new WaitForEndOfFrame());
                }
            }
        }
Ejemplo n.º 16
0
        // Update is called once per frame
        void Update()
        {
            //Establish a world connection.
            if (ws_ != null)
            {
                string reply = ws_.RecvString();
                if (reply != null)
                {
                    //deserialize
                    //eqemu json start
                    OpcodeFromServerClass IdChecker1 = JsonConvert.DeserializeObject <OpcodeFromServerClass> (reply);

                    if (IdChecker1.id != null && IdChecker1.id == "token_auth_id")
                    {
                        if (CSel != null)
                        {
                            CSel.LoginStatus.text = "Auth successful. Proceeding...";
                        }
                    }
                    if (IdChecker1.method == "Client.Opcode")
                    {
                        byte[] RawData = null;
                        if (Convert.ToInt32(IdChecker1.datasize) > 0)
                        {
                            RawData = System.Convert.FromBase64CharArray(IdChecker1.data.ToCharArray(), 0, IdChecker1.data.Length);
                        }

                        if (opcodeDict.ContainsKey(IdChecker1.opcode))
                        {
                            string RawOp = IdChecker1.opcode;

                            int length = 0;
                            if (RawData != null)
                            {
                                length = RawData.Length;
                            }
                            opcodeDict[RawOp](RawData, length);
                        }
                    }
                }
                if (ws_.Error != null)
                {
                    LogError("Error: " + ws_.Error);
                    ws_ = null;
                    if (CSel != null)
                    {
                        CSel.BackToLogin();
                    }
                }
            }
        }
Ejemplo n.º 17
0
    private void CheckWebsocket()
    {
        string reply = w.RecvString();

        if (reply == null)
        {
            return;
        }

        Debug.Log("got websocket message: " + reply);
        TurnEvent turnEvent = JsonUtility.FromJson <TurnEvent>(reply);

        goToGame(turnEvent);
    }
Ejemplo n.º 18
0
        private IEnumerator Dispatcher()
        {
            while (connectorInstanceId == Connector.GetHashCode())
            {
                var received = Connector.RecvString();
                if (received == null)
                {
                    yield return(null);

                    continue;
                }
                HandleOnTextMessageRecv(received);
            }
        }
Ejemplo n.º 19
0
    IEnumerator ReceiveData()
    {
        yield return(new WaitForSeconds(5));

        if (_webSocket != null)
        {
            print("Receive test data...");
            string inputMsg = _webSocket.RecvString();
            print(inputMsg);
        }
        else
        {
            yield return(0);
        }
    }
Ejemplo n.º 20
0
        // Update is called once per frame
        void Update()
        {
            //Establish a world connection.
            if (ws_ != null)
            {
                string reply = ws_.RecvString();
                if (reply != null)
                {
//					Debug.Log("reply" + reply);
                    OpcodeFromServerClass IdChecker1 = JsonUtility.FromJson <OpcodeFromServerClass> (reply);

                    if (IdChecker1.id != null && IdChecker1.id == "token_auth_id")
                    {
                        if (CSel != null)
                        {
                            CSel.LoginStatus.text = "Auth successful. Proceeding...";
                        }
                    }
                    if (IdChecker1.method == "Client.Opcode")
                    {
                        byte[] RawData = null;
                        if (Convert.ToInt32(IdChecker1.datasize) > 0)
                        {
                            RawData = System.Convert.FromBase64CharArray(IdChecker1.data.ToCharArray(), 0, IdChecker1.data.Length);
                        }

                        if (opcodeDict.ContainsKey(IdChecker1.opcode))
                        {
                            string RawOp = IdChecker1.opcode;

                            int length = 0;
                            if (RawData != null)
                            {
                                length = RawData.Length;
                            }
                            opcodeDict[RawOp](RawData, length);
                        }
                    }
                }
                if (ws_.Error != null)
                {
                    LogError("Error: " + ws_.Error);
                    ws_ = null;
                    SceneManager.LoadScene("1 Character creation");
                    Destroy(WorldConnectObject);
                }
            }
        }
Ejemplo n.º 21
0
    // Use this for initialization
    IEnumerator Start()
    {
        string uri = "ws://178.62.226.87:8000/";

        WebSocket w = new WebSocket(new Uri(uri));

        yield return(StartCoroutine(w.Connect()));

        print("Started websocket server at: " + uri);

        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                if (isValidMessage(reply))
                {
                    string id = parsePlayerId(reply);

                    if (!playerManager.hasPlayer(id))
                    {
                        playerManager.createPlayer(id);
                    }

                    Runner currentRunner = playerManager.getPlayer(id);

                    if (reply.Contains("rotation"))
                    {
                        float speed = parseSpeed(reply);
                        print("Speed: " + speed);
                        currentRunner.setLastSpeed(speed);
                    }
                    else if (reply.Contains("jump"))
                    {
                        currentRunner.setShouldJump();
                    }
                }
            }
            if (w.Error != null)
            {
                Debug.LogError("Error: " + w.Error);
                break;
            }
            yield return(0);
        }
        w.Close();
    }
Ejemplo n.º 22
0
    void ListenServerMessage()
    {
        string replyStr = ws.RecvString();

        if (replyStr != null)
        {
            //Debug.Log("raw replyStr=" + replyStr);
            strMessagesFromServer.Enqueue(replyStr);
        }

        byte[] replyBytes = ws.Recv();
        if (replyBytes != null)
        {
            //Debug.Log("raw replyBytes=" + replyBytes.ToString());
            bytesMessagesFromServer.Enqueue(replyBytes);
        }
    }
    // Use this for initialization
    IEnumerator Start()
    {
        DontDestroyOnLoad(this.gameObject);

        InitHandlers();

        socket = new WebSocket(new Uri("ws://localhost:9000/"));
        yield return(StartCoroutine(socket.Connect()));

        while (true)
        {
            string reply = socket.RecvString();

            if (reply != null)
            {
                JSONNode data = JSON.Parse(reply);

                string type = data [1];

//				Debug.Log("Received message: " + type);

                if (handlers[type] != null)
                {
                    StartCoroutine(handlers [type] (data));
                }
                else
                {
                    Debug.Log("Invalid message: " + type);
                }
            }

            if (socket.error != null)
            {
                Debug.Log("Error: " + socket.error);

                yield return(new WaitForSeconds(1));

                socket = new WebSocket(new Uri("ws://localhost:9000/"));
                yield return(StartCoroutine(socket.Connect()));
            }

            yield return(0);
        }

//		socket.Close();
    }
Ejemplo n.º 24
0
    IEnumerator StreamNotifications()
    {
        WebSocket w = new WebSocket(new Uri("wss://stream.pushbullet.com/websocket/o.czs8GXB8DKYttsEtWsBb991gQdHSsGSE"));

        yield return(StartCoroutine(w.Connect()));

        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                Debug.Log("Received: " + reply);
                var resp = JSON.Parse(reply);
                if (resp["type"] == "push")
                {
                    if (resp["push"]["type"] == "sms_changed" && resp["push"]["notifications"][0]["title"] != null)
                    {
                        Debug.Log(resp["push"]["notifications"][0]["title"] + ": " + resp["push"]["notifications"][0]["body"]);
                    }
                    if (resp["push"]["type"] == "mirror")
                    {
                        if (resp["push"]["application_name"] == "Messenger")
                        {
                            Debug.Log(resp["push"]["title"] + ": " + resp["push"]["body"]);
                        }
                        if (resp["push"]["application_name"] == "Pushbullet" && resp["push"]["title"] == "Incoming call")
                        {
                            Debug.Log(resp["push"]["title"] + " at " + DateTime.Now.ToShortTimeString());
                        }
                        if (resp["push"]["application_name"] == "Gmail")
                        {
                            Debug.Log("New email from " + resp["push"]["title"]);
                        }
                    }
                }
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }
            yield return(0);
        }
        w.Close();
    }
Ejemplo n.º 25
0
    IEnumerator Listen()
    {
        while (true)
        {
            if (!ws.IsConnected() || ws.error != null)
            {
                Close();
                yield break;
            }

            string reply;
            while ((reply = ws.RecvString()) != null)
            {
                Debug.Log(reply);
            }

            yield return(null);
        }
    }
Ejemplo n.º 26
0
    private IEnumerator ListenSocket()
    {
        while (true)
        {
            if (!ws.IsConnected() || ws.error != null)
            {
                Close();
                yield break;
            }

            string reply;
            while ((reply = ws.RecvString()) != null)
            {
                Message.ParseMessage(reply, this.onStateReceived, this.onBoardReceived);
            }

            yield return(null);
        }
    }
Ejemplo n.º 27
0
    IEnumerator Start()
    {
        this.go = commandReceiver;
        this.allowedCommands = new Dictionary <string, Type>();

        Debug.Log("Connecting to server");
        // connect to server
        webSocket = new WebSocket(new Uri("ws://localhost:8000"));
        yield return(StartCoroutine(webSocket.Connect()));

        Debug.Log("CONNECTED TO WEBSOCKETS");
        var x = new PlayerWantsToJoinCommand()
        {
            gameId   = 4,
            name     = "afsd",
            playerId = Guid.Empty
        };

        this.sendToAll(x);
        // wait for messages
        while (true)
        {
            // read message
            string message = webSocket.RecvString();
            // check if message is not empty
            if (message != null)
            {
                this.recv(message);
            }
            // Debug.Log("RECEIVED FROM WEBSOCKETS: " + reply);
            // if connection error, break the loop
            if (webSocket.error != null)
            {
                Debug.LogError("Error: " + webSocket.error);
                break;
            }

            yield return(0);
        }
        // if error, close connection
        webSocket.Close();
    }
Ejemplo n.º 28
0
 IEnumerator StartListener()
 {
     while (true)
     {
         List <string> replies = m_socket.RecvString(1);
         for (int i = 0; i < replies.Count; i++)
         {
             string reply = replies[i];
             if (reply != null)
             {
                 HandleMessage(reply);
             }
             if (m_socket.error != null)
             {
                 Debug.LogError(m_socket.error);
             }
         }
         yield return(0);
     }
 }
Ejemplo n.º 29
0
    IEnumerator ConnectWebsocket()
    {
        log("Connecting...");
        yield return(StartCoroutine(w.Connect()));

        log("Connecting...2");
        while (w.error == "Closed")
        {
            yield return(StartCoroutine(ReconnectWebsocket()));

            log("Closed connection");
        }

        connected = true;
        log("CONNECTED WEBSOCKET");

        while (true)
        {
            reply = w.RecvString();
            if (reply != null && reply != "Null")
            {
                FlowEvent incoming = JsonUtility.FromJson <FlowEvent>(reply);
                CommandProcessor.processCommand(incoming);
            }
            if (w.error != null)
            {
                log("[unity] Error: " + w.error);
                connected = false;

                yield return(new WaitForSeconds(5));

#if !UNITY_WSA
                DoOnMainThread.ExecuteOnMainThread.Enqueue(() =>
                {
                    StartCoroutine(ConnectWebsocket());
                });
#endif
            }
            yield return(0);
        }
    }
Ejemplo n.º 30
0
    private string _receiveStr = null;  //记录接收到的信息

    private IEnumerator Start()
    {
        _ws = new WebSocket(new Uri("ws://127.0.0.1:8730/Test"));
        yield return(StartCoroutine(_ws.Connect()));

        //AddText(NoticeTxt, "Successfully connect to the server!");
        while (true)
        {
            string reply = _ws.RecvString();
            if (reply != null)
            {
                OnReceive(reply);
            }
            if (_ws.error != null)
            {
                Debug.LogError("Error: " + _ws.error);
                break;
            }
            yield return(0);
        }
    }
Ejemplo n.º 31
0
    void Update()
    {
        try
        {
            reply = w.RecvString();
        }
        catch (Exception e)
        {
            Debug.LogError("Error: " + e.ToString());
            // break;
        }

        if (reply != null)
        {
            Debug.Log("Received: " + reply);
        }
        if (w.error != null)
        {
            Debug.LogError("Error: " + w.error.ToString());
        }
    }
Ejemplo n.º 32
0
	// Use this for initialization
	IEnumerator Start () {
        WebSocket w = new WebSocket(new Uri("ws://192.168.1.206:8888/ws"));
		yield return StartCoroutine(w.Connect());
		w.SendString("UnityTest");
		int i=0;
		while (true)
		{
			string reply = w.RecvString();
			if (reply != null)
			{
				Debug.Log ("Received: "+reply);
                w.SendString("UnityTest " + i++);
			}
			if (w.Error != null)
			{
				Debug.LogError ("Error: "+w.Error);
				break;
			}
			yield return 0;
		}
		w.Close();
	}
Ejemplo n.º 33
0
    private IEnumerator ClientLoop()
    {
        webSocket = new WebSocket(new Uri("ws://" + address + ":" + port + "/" + optionalWebhook));
        yield return(StartCoroutine(webSocket.Connect()));

        while (true)
        {
            string reply = webSocket.RecvString();
            if (reply != null)
            {
                Debug.Log("Received: " + reply);
                DecodeJSON(reply);
            }
            if (webSocket.error != null)
            {
                Debug.LogError("Error: " + webSocket.error);
                break;
            }
            yield return(null);
        }
        webSocket.Close();
    }
Ejemplo n.º 34
0
 // Use this for initialization
 IEnumerator Start()
 {
     WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:3000"));
     yield return StartCoroutine(w.Connect());
     w.SendString("Hi there");
     int i = 0;
     while(true)
     {
         string reply = w.RecvString();
         if(reply != null)
         {
             Debug.Log("Received: " + reply);
             w.SendString("Hi there" + i++);
         }
         if(w.Error != null)
         {
             Debug.LogError("Error: " + w.Error);
             break;
         }
         yield return 0;
     }
     w.Close();
 }
Ejemplo n.º 35
0
        IEnumerator Connecting()
        {
            var env = ConstantEnviroment.Instance;
            string uri = env.Network.GetAddress(env.Scene.GetPort(SceneManager.GetActiveScene().name));
            Debug.Log("[Connecting] IP=" + uri + " Group=" + MyPlayerController.Instance.Group);
            var socket = new WebSocket(new Uri(uri));
            yield return StartCoroutine(socket.Connect());

            JsonHash hash = new SyncStatus() { Group = MyPlayerController.Instance.Group, Status = NetworkStatus.Join }.ToHash();
            socket.SendString(Json.Serialize(new JsonList() { hash }));

            while (true)
            {
                yield return null;
                var recv = socket.RecvString();
                Retrieve(recv);
                while(_SynchronizedQueue.Count > 0)
                {
                    Synchronized s = _SynchronizedQueue.Dequeue();
                    SyncStatus status = s as SyncStatus;
                    if (status == null) continue;

                    if (status.Status == NetworkStatus.Accept)
                    {
                        // サーバーと接続できた時
                        Synchronized.MyGroup = status.Group;	// 自分のGroupを登録
                        Synchronized.MyId = status.ShortId;	// 自分のIDを登録
                        MyPlayerController.Instance.SetID(status.Group, status.ShortId);
                        _StartTime = status.Time;	// 始まった時間
                        _WebSocket = socket;	// ソケット登録
                        Debug.Log("[Connected] Group=" + status.Group + " ID=" + Synchronized.MyId + " Time=" + _StartTime);
                        yield break;
                    }
                }
            }
        }
    public IEnumerator ConnectToWebSocket_InThread(string controllerName)
    {
        Debug.Log("Connection to WebSocket"); //Show received message from server
        //websocketConnection = new WebSocket(new Uri("ws://" + IPAdress + ":" + PortNumber + ControllerName));
        websocketConnection = new WebSocket(new Uri("ws://" + IPAdress + ":" + PortNumber + controllerName));

        yield return StartCoroutine(websocketConnection.Connect());
        SendPackageToServer("CheckConnection");
        //StartCoroutine();

        while (true)
        {
            string answerMessage = websocketConnection.RecvString();
            if (answerMessage != null)
            {
                yield return StartCoroutine(AnswerParser(answerMessage)); //Debug
            }
            if (websocketConnection.Error != null)
            {
                Debug.Log("Error: " + websocketConnection.Error);
                connectionManager.Callback_ServerConnect(false);
                //DisconnectFromWebSocket();
                //ConnectToWebSocket(ControllerName);
                break;
            }
            yield return 0;
        }
    }
Ejemplo n.º 37
0
    // Use this for initialization
    IEnumerator StartWebSocket_CR()
    {
        WebSocket w = new WebSocket(new Uri("ws://128.2.236.66:3000"));
        yield return StartCoroutine(w.Connect());

		w.SendString("Ctrl Connected");
        while (true)
        {
            string res = w.RecvString();
			if (res != null)
            {
#if UNITY_EDITOR
                Debug.Log("Received: " + res);
#endif
                //w.SendString("Hi there" + i++);
                char[] delimiterChars = { ' ' ,'\t' };
				string[] parseStr = res.Split(delimiterChars);

				switch(parseStr[0]){
					case "m+":{
					_crowdSim.globalAttentionMean = SetValueFromString(_crowdSim.globalAttentionMean, true, parseStr);
						break;
					}
					case "m-":{
					_crowdSim.globalAttentionMean = SetValueFromString(_crowdSim.globalAttentionMean, false, parseStr);
						break;
					}
					case "d+":{
					_crowdSim.globalAttentionStDev = SetValueFromString(_crowdSim.globalAttentionStDev, true, parseStr);
						break;
					}
					case "d-":{
						_crowdSim.globalAttentionStDev = SetValueFromString(_crowdSim.globalAttentionStDev, false, parseStr);
						break;
					}
					case "u+":{
						_crowdSim.seatPosAttentionUpper = SetValueFromString(_crowdSim.seatPosAttentionUpper, true, parseStr);
						break;
					}
					case "u-":{
						_crowdSim.seatPosAttentionUpper = SetValueFromString(_crowdSim.seatPosAttentionUpper, false, parseStr);
						break;
					}
					case "l+":{
						_crowdSim.seatPosAttentionLower = SetValueFromString(_crowdSim.seatPosAttentionLower, true, parseStr);
						break;
					}
					case "l-":{
						_crowdSim.seatPosAttentionLower = SetValueFromString(_crowdSim.seatPosAttentionLower, false, parseStr);
						break;
					}

				}
			
				w.SendString("|Unity> currStat: m=" + _crowdSim.globalAttentionMean + ", dev=" + _crowdSim.globalAttentionStDev 
				             + ", A_up=" + _crowdSim.seatPosAttentionUpper + ", A_Low=" +  _crowdSim.seatPosAttentionLower + "." );

				
				//w.SendString("|Unity> blar blar" + res);

            }
            if (w.Error != null)
            {
#if UNITY_EDITOR
                Debug.Log("Error: " + w.Error);
#endif
                break;
            }
            yield return 0;
        }
        w.Close();
    }
Ejemplo n.º 38
0
    // Use this for initialization
    IEnumerator Start()
    {
        WebSocket w = new WebSocket(new Uri("ws://178.62.242.126:8000/"));
        yield return StartCoroutine(w.Connect());
        int i=0;
        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                float newAccelerationTarget = parseAcceleration(reply);
                if(newAccelerationTarget > 0.1f){

                    accelerationTargetReached = false;
                    accelerationTarget = 1.0f;
                }

                moveCharacter();
                Debug.Log ("Received: "+reply);
            }
            if (w.Error != null)
            {
                Debug.LogError ("Error: "+w.Error);
                break;
            }
            yield return 0;
        }
        w.Close();
    }
Ejemplo n.º 39
0
    /// Use this for initialization
    IEnumerator StartCommunicator()
    {
        WebSocket w = new WebSocket(new Uri("ws://192.168.33.138:8080"));
        if(!testLocally) {
            yield return StartCoroutine(w.Connect());
            w.SendString("Hi there, I'm the communicator");
        }
        int i=0;
        while (true)
        {
            sendingIntervalCountdown -= Time.deltaTime;
            if(sendingIntervalCountdown < 0) {
                sendingIntervalCountdown = sendingInterval;
                String toSend = "{\"x\":"+ball.position.x+",\"y\":"+ball.position.z+",\"z\":"+ball.position.y+"}";
                Debug.Log(toSend);
                if(!testLocally) {
                    w.SendString (toSend);
                }
            }
            string reply = null;
            if(!testLocally) {
                reply = w.RecvString();
            } else {
                reply = localTestCommand;
                localTestCommand = null;
            }
            if (reply != null)
            {
                Debug.Log ("Received: "+reply);
                Vector3 force = Vector3.zero;
                /*if(reply != null && reply.Length == ) {
                    if(reply[0] == '#') {

                    }
                }*/
                switch(reply) {
                case "jump":
                    force = new Vector3(0, 300, 0);
                    break;
                case "left":
                    force = new Vector3(500, 0, 0);
                    break;
                case "right":
                    force = new Vector3(-500, 0, 0);
                    break;
                case "forward":
                    force = new Vector3(0, 0, 500);
                    break;
                case "backward":
                    force = new Vector3(0, 0, -500);
                    break;
                case "color":
                    force = new Vector3(0, 0, -500);
                    break;
                }
                //Debug.Log (force);
                ball.GetComponent<Rigidbody>().AddForce(force);
                //w.SendString("Hi there"+i++);
            }
            if (!testLocally && w.error != null)
            {
                Debug.LogError ("Error: "+w.error);
                break;
            }
            yield return 0;
        }
        w.Close();
    }