예제 #1
0
    /// <summary>
    /// Open to receive messages on specified port and (optionally) from specified multicast IP address.
    /// Returns success status.
    /// </summary>
    public bool Open(int port, string multicastAddress = "")
    {
        // Ensure that we have a receiver, even when not in Play mode.
        if (_receiver == null)
        {
            _receiver = new UdpReceiver(OnDataReceivedAsync);
        }

        // Close and existing receiver.
        if (isOpen)
        {
            Close();
        }

        // Validate port number range.
        if (port < OscConst.portMin || port > OscConst.portMax)
        {
            StringBuilder sb = OscDebug.BuildText(this);
            sb.Append("Open failed. Port "); sb.Append(port); sb.Append(" is out of range.\n");
            Debug.LogWarning(sb.ToString());
            return(false);
        }
        _port = port;

        // Derive mode from multicastAddress.
        IPAddress multicastIP;

        if (!string.IsNullOrEmpty(multicastAddress) && IPAddress.TryParse(multicastAddress, out multicastIP))
        {
            if (Regex.IsMatch(multicastAddress, OscConst.multicastAddressPattern))
            {
                _mode             = OscReceiveMode.UnicastBroadcastMulticast;
                _multicastAddress = multicastAddress;
            }
            else
            {
                StringBuilder sb = OscDebug.BuildText(this);
                sb.Append("Open failed. Multicast IP address "); sb.Append(multicastAddress);
                sb.Append(" is out not valid. It must be in range 224.0.0.0 to 239.255.255.255.\n");
                Debug.LogWarning(sb.ToString());
                return(false);
            }
        }
        else
        {
            _multicastAddress = string.Empty;
            _mode             = OscReceiveMode.UnicastBroadcast;
        }

        // Set buffer size.
        _receiver.bufferSize = _udpBufferSize;

        // Try open.
        if (!_receiver.Open(_port, _multicastAddress))
        {
            Debug.Log("Failed to open");
            return(false);
        }

        // Deal with the success
        if (Application.isPlaying)
        {
            StringBuilder sb = OscDebug.BuildText(this);
            if (_mode == OscReceiveMode.UnicastBroadcast)
            {
                sb.Append("Ready to receive unicast and broadcast messages on port ");
            }
            else
            {
                sb.Append("Ready to receive multicast messages on address "); sb.Append(_multicastAddress); sb.Append(", unicast and broadcast messages on port ");
            }
            sb.Append(_port); sb.AppendLine();
            Debug.Log(sb.ToString());
        }

        return(true);
    }