Example #1
0
        public void OnDisable()
        {
            if (sender != null)
            {
                SendBeacon(false);
            }

            stopSender?.Set();
            stopCleaner?.Set();

            if (broadcast != null)
            {
                broadcast.onReceive.RemoveListener(OnReceive);
            }

            sender?.Join();
            cleaner?.Join();

            stopSender?.Dispose();
            stopCleaner?.Dispose();

            discovered.Clear();

            sender      = null;
            cleaner     = null;
            stopSender  = null;
            stopCleaner = null;
        }
Example #2
0
        protected void Awake()
        {
            // Make sure that singleton is initialized in Unity thread before first use
            Threads.APC.MonoBehaviourCall.Instance.GetType();

            if (Utils.PortManager.Instance.ReservePort(port))
            {
                localAddresses     = new HashSet <IPAddress>();
                broadcastAddresses = new List <IPEndPoint>();

                foreach (NetworkInterface net in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (net != null && (net.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || net.NetworkInterfaceType == NetworkInterfaceType.Ethernet))
                    {
                        foreach (UnicastIPAddressInformation unicast_info in net.GetIPProperties().UnicastAddresses)
                        {
                            if (unicast_info.Address.AddressFamily == AddressFamily.InterNetwork)
                            {
                                byte[] address = unicast_info.Address.GetAddressBytes();
                                byte[] mask    = unicast_info.IPv4Mask.GetAddressBytes();

                                for (int i = 0; i < address.Length && i < mask.Length; i++)
                                {
                                    address[i] |= (byte)~mask[i];
                                }

                                IPAddress broadcast = new IPAddress(address);

                                localAddresses.Add(unicast_info.Address);
                                broadcastAddresses.Add(new IPEndPoint(broadcast, port));
                            }
                        }
                    }
                }

                udp = new UdpClient()
                {
                    ExclusiveAddressUse = !broadcastToLocalhost,
                    EnableBroadcast     = true
                };

                // To send/receive on the same host.
                udp.Client.MulticastLoopback = broadcastToLocalhost;
                udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, broadcastToLocalhost);

                udp.Client.Bind(new IPEndPoint(IPAddress.Any, port));

                stop = new ManualResetEvent(false);

                thread = new Threads.Thread(Listener);

                thread.Start();
            }
        }
Example #3
0
        protected void OnDestroy()
        {
            stop.Set();

            thread.Join();

            udp.Dispose();

            stop.Dispose();

            udp    = null;
            thread = null;
            stop   = null;
        }
Example #4
0
        protected void OnEnable()
        {
            if (sender == null)
            {
                stopSender  = new ManualResetEvent(false);
                stopCleaner = new ManualResetEvent(false);

                broadcast.onReceive.AddListener(OnReceive);

                sender  = new Threads.Thread(Sender);
                cleaner = new Threads.Thread(Cleaner);

                sender.Start();
                cleaner.Start();
            }
        }
Example #5
0
        public Base(Negotiation.Base parent, Message.Negotiation.Parameters parameters, UnityAction <Base> disconnection_handler)
        {
            this.parent     = parent;
            this.parameters = parameters;

            events = new ChannelEvents();
            events.onDisconnectedHandler = new ChannelEvents.DisonnectionHandlerCallback();
            events.onDisconnectedHandler.AddListener(disconnection_handler);

            sendResult = null;

            sendQueue = new Queue <Threads.Task>();

            stopEvent = new ManualResetEvent(false);
            addEvent  = new ManualResetEvent(false);

            worker = new Threads.Thread(Worker);
        }
Example #6
0
		public Server(ushort port, Dictionary<string, Endpoint> endpoints)
		{
			if(!HttpListener.IsSupported)
			{
				throw new NotSupportedException("HTTP server is not support on this implementation.");
			}

			// Initialize unity objects in unity thread
			Threads.APC.MonoBehaviourCall.Instance.GetType();

			this.endpoints = endpoints;

			stopEvent = new ManualResetEvent(false);

			listener = new HttpListener();
			listener.Prefixes.Add(string.Format("http://*:{0}/", port));
			listener.Start();

			listenerWorker = new Threads.Thread(Listen);
			listenerWorker.Start();
		}
Example #7
0
        public override void Disconnect()
        {
            if (state == State.RUNNING || state == State.CLOSING)
            {
                if (listener != null)
                {
                    listener.Stop();
                }

                if (stopEvent != null)
                {
                    stopEvent.Set();
                }

                CloseInitializedConnections();

                CloseOpenedChannels();

                CloseMonitors();

                if (listenerThread != null)
                {
                    listenerThread.Join();
                }

                if (stopEvent != null)
                {
                    stopEvent.Close();
                }

                serverCertificate = null;
                listenerThread    = null;
                stopEvent         = null;

                state = State.STARTED;
            }
        }
Example #8
0
        public void Listen()
        {
            if (state == State.STARTED)
            {
                state = State.INITIALIZING;

                availablePorts.Remove(port);

                stopEvent = new ManualResetEvent(false);

                serverCertificate = null;

                // Should we use an encrypted channel?
                if (certificate != null && certificate.bytes.Length > 0)
                {
                    string tmp_file = string.Format("{0}{1}{2}", Application.temporaryCachePath, Path.DirectorySeparatorChar, certificate.name);

                    File.WriteAllBytes(tmp_file, certificate.bytes);

                    try
                    {
#if !UNITY_WSA
                        // Import the certificate
                        serverCertificate = new X509Certificate2(tmp_file);
#else
                        // At the moment, SslStream is not working on Hololens platform.
                        // Indeed, at the moment, player capabilities does not provide a way to authorize access to the trusted root certificates store.
                        throw new NotSupportedException("SSL streams are not supported on Hololens.");
#endif
                    }
                    catch (Exception)
                    {
                        Debug.LogWarningFormat("Invalid certificate file '{0}'. Encryption is disabled.", certificate.name);

                        serverCertificate = null;
                    }

                    File.Delete(tmp_file);
                }

                listener = new TcpListener(IPAddress.Any, port);
                listener.Start();

                listenerThread = new Threads.Thread(() =>
                {
                    while (state < State.CLOSING && !stopEvent.WaitOne(0))
                    {
                        try
                        {
                            // Listen for new connections
                            IAsyncResult context = listener.BeginAcceptTcpClient(AcceptClient, null);

                            // Wait for next connection or exit signal
                            if (WaitHandle.WaitAny(new[] { stopEvent, context.AsyncWaitHandle }) == 0)
                            {
                                return;
                            }
                        }
                        catch (InvalidOperationException)
                        {
                            // Happens when disposing of listener while listening for new connection.
                            // Nothing to do, just exit the thread to close cleanly.
                        }
                    }
                });
                listenerThread.Start();

                Debug.LogFormat("Started server on port {0}", port);

                state = State.RUNNING;
            }
            else
            {
                Debug.LogErrorFormat("Invalid initialization attempt of server when in state {0}.", state);
            }
        }