Пример #1
0
    /// <summary>
    /// General update routine.
    /// </summary>
    public void Update()
    {
        // KEYBOARD INTERACTION for demonstration purposes
        //

        // C - connect to WebSocket Server
        if (Input.GetKeyDown(KeyCode.C))
        {
            Debug.Log("[WebSocketServerConnector] C pressed");

            if (websocket != null)
            {
                Debug.Log("[WebSocketServerConnector] Initiate connection to configured WebSocket server.");
                websocket.Connect();
            }
        }

        // S - send message from Unity to JavaScript via WebSocket Server
        if (Input.GetKeyDown(KeyCode.S))
        {
            Debug.Log("[WebSocketServerConnector] S pressed");

            if (websocket != null)
            {
                Debug.Log("[WebSocketServerConnector] Send a DefaultMessage to the WebSocket server.");

                // construct an example DefaultMessage
                MessageJSONAPI.DefaultMessage message = new MessageJSONAPI.DefaultMessage("Unity3D client", "JavaScript client", UNITYsendMessageToJAVASCRIPT, "An example string from Unity to JavaScript via Node.js.", 42, 23.7f, true);

                // create JSON string based on message object's properties
                string jsonStringMessage = JsonUtility.ToJson(message);

                // send string to WebSocket server
                websocket.Send(jsonStringMessage);
            }
        }
    }
Пример #2
0
    /// <summary>
    /// Instantiation and dynamic reference set up.
    /// </summary>
    public void Awake()
    {
        // check if helper instance is set up
        if (webSocketReceivedMessageHandler == null)
        {
            Debug.LogError("[WebSocketServerConnector] WebSocketReceivedMessageHandler is not assigned.");
        }

        // instantiate new WebSocket object using the specified server url
        websocket = new WebSocket(WEBSOCKET_SERVER_URL);

        // configure WebSocket event listeners if instantiation was successful
        if (websocket != null)
        {
            // Event Handler: OnOpen
            websocket.OnOpen += (sender, e) =>
            {
                Debug.Log("[WebSocketServerConnector] Connection established to WSS Server.");
            };

            // Event Handler: OnClose
            websocket.OnClose += (sender, e) =>
            {
                Debug.LogWarning("[WebSocketServerConnector] OnClose event received.");
                websocket.Close();
            };

            // Event Handler: OnClose
            websocket.OnError += (sender, e) =>
            {
                Debug.LogError("[WebSocketServerConnector] OnError event received.");
            };

            // Event Handler: OnMessage
            websocket.OnMessage += (sender, e) =>
            {
                // determine type of message event

                // text (== string) data received
                if (e.IsText)
                {
                    Debug.Log("[WebSocketServerConnector] OnMessage received with TEXT data: " + e.Data);

                    // parse received message formatted in JSON, and create an object accordingly
                    MessageJSONAPI.DefaultMessage receivedJsonMessage = JsonUtility.FromJson <MessageJSONAPI.DefaultMessage>(e.Data);

                    // access / use parsed JSON data
                    Debug.Log(receivedJsonMessage);
                    Debug.Log(receivedJsonMessage.sender);
                    Debug.Log(receivedJsonMessage.receiver);
                    Debug.Log(receivedJsonMessage.api);
                    Debug.Log(receivedJsonMessage.valueString);
                    Debug.Log(receivedJsonMessage.valueInt);
                    Debug.Log(receivedJsonMessage.valueFloat);
                    Debug.Log(receivedJsonMessage.valueBool);

                    // determine what to do next based on determined API field
                    switch (receivedJsonMessage.api)
                    {
                    case JAVASCRIPTsendMessageToUNITY:
                        Debug.Log("Message received from JavaScript client.");
                        // do something

                        // === update from 2021-02-23 ===
                        // Generally, data structure manipulation is possible directly from within this event, but not Unity GameObject-related manipulations.
                        // As a work-around, the WebSocketReceivedMessageHandler class was created (see its documentation for further information).

                        // hand over received message to WebSocketReceivedMessageHandler, responsible for further handling of any desired (and Unity GameObject-related) actions in the application
                        webSocketReceivedMessageHandler.queueDefaultMessage(receivedJsonMessage);
                        break;

                    default:
                        break;
                    }
                }

                // binary data received
                else if (e.IsBinary)
                {
                    Debug.Log("[WebSocketServerConnector] OnMessage received with BINARY raw data: " + e.RawData);
                }

                // ping received
                else if (e.IsPing)
                {
                    Debug.Log("[WebSocketServerConnector] OnMessage ping received from server.");
                }

                // data could not be determined
                else
                {
                    Debug.Log("[WebSocketServerConnector] Message received with UNDETERMINED data: " + e.Data);
                }
            };
        }
    }