Ejemplo n.º 1
0
 async Task <bool> InitializeMulticastRecv()
 {
     try
     {
         if (msocketRecv != null)
         {
             msocketRecv.MessageReceived -= UDPMulticastMessageReceived;
             msocketRecv.Dispose();
             msocketRecv = null;
         }
         msocketRecv = new DatagramSocket();
         msocketRecv.Control.MulticastOnly = true;
         msocketRecv.MessageReceived      += UDPMulticastMessageReceived;
         NetworkAdapter adapter = GetDefaultNetworkAdapter(SendInterfaceAddress);
         if (adapter != null)
         {
             await msocketRecv.BindServiceNameAsync(MulticastUDPPort.ToString(), adapter);
         }
         else
         {
             await msocketRecv.BindServiceNameAsync(MulticastUDPPort.ToString());
         }
         HostName mcast = new HostName(MulticastIPAddress);
         msocketRecv.JoinMulticastGroup(mcast);
         return(true);
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine("Exception while listening: " + e.Message);
     }
     return(false);
 }
Ejemplo n.º 2
0
        async Task <bool> InitializeUnicastRecv()
        {
            try
            {
                if (usocketRecv != null)
                {
                    usocketRecv.MessageReceived -= UDPUnicastMessageReceived;
                    usocketRecv.Dispose();
                    usocketRecv = null;
                }
                usocketRecv = new DatagramSocket();
                usocketRecv.MessageReceived += UDPUnicastMessageReceived;
                //  NetworkAdapter adapter = GetDefaultNetworkAdapter();
                //  if (adapter != null)
                //      await msocketRecv.BindServiceNameAsync(UnicastUDPPort.ToString(), adapter);
                //  else
                await usocketRecv.BindServiceNameAsync(UnicastUDPPort.ToString());

                return(true);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception while listening: " + e.Message);
            }
            return(false);
        }
Ejemplo n.º 3
0
        async Task <bool> InitializeSend()
        {
            bool result = false;

            try
            {
                if (msocketSend != null)
                {
                    msocketSend.Dispose();
                    msocketSend = null;
                }
                msocketSend = new DatagramSocket();

                NetworkAdapter adapter = GetDefaultNetworkAdapter(SendInterfaceAddress);
                if (adapter != null)
                {
                    await msocketSend.BindServiceNameAsync("", adapter);
                }
                result = true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception while initializing: " + e.Message);
                result = false;
            }
            return(result);
        }
Ejemplo n.º 4
0
        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            Send.IsEnabled = false;
            var socket = new DatagramSocket();

            try
            {
                var    address = Address.Text.Split(':');
                string host = address[0], port = address[1];
                await socket.BindServiceNameAsync("1902");

                var outputStream = await socket.GetOutputStreamAsync(new HostName(host), port);

                var writer = new DataWriter(outputStream);
                writer.WriteString(Message.Text);
                await writer.StoreAsync();

                socket.Dispose();
            }
            catch (Exception ex)
            {
                logger.WriteLine(ex.ToString());
            }
            finally
            {
                socket.Dispose();
                Send.IsEnabled = true;
            }
        }
Ejemplo n.º 5
0
 public async Task <bool> InitializeRecv()
 {
     recvInitialized = false;
     try
     {
         if (msocketRecv != null)
         {
             msocketRecv.MessageReceived -= UDPMulticastMessageReceived;
             msocketRecv.Dispose();
             msocketRecv = null;
         }
         msocketRecv = new DatagramSocket();
         msocketRecv.MessageReceived += UDPMulticastMessageReceived;
         NetworkAdapter adapter = GetDefaultNetworkAdapter();
         if (adapter != null)
         {
             await msocketRecv.BindServiceNameAsync(mPort);
         }
         //              await msocketRecv.BindServiceNameAsync(mPort, adapter);
         else
         {
             await msocketRecv.BindServiceNameAsync(mPort);
         }
         HostName mcast = new HostName(mAddress);
         msocketRecv.JoinMulticastGroup(mcast);
         mLastIDReceived = 0;
         recvInitialized = true;
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine("Exception while listening: " + e.Message);
         recvInitialized = false;
     }
     return(recvInitialized);
 }
Ejemplo n.º 6
0
        public async Task SsdpQueryAsync(string filter = "ssdp:all", int seconds = 5, int port = 1900)
        {
            _ssdpPort     = port;
            _foundDevices = new List <string>();
            var remoteIP  = new Windows.Networking.HostName(_ssdp_ip);
            var ssdpQuery = GetSSDPQuery(seconds, port, filter);
            var reqBuff   = Encoding.UTF8.GetBytes(ssdpQuery);

            try
            {
                if (_readerSocket != null)
                {
                    _readerSocket.Dispose();
                }
            }
            catch (Exception ex)
            {
                LogException("SSDPFinder.QueryAsync - Close Existing Socket", ex);
            }

            _readerSocket = new DatagramSocket();
            _readerSocket.MessageReceived += (sender, args) =>
            {
                Task.Run(async() =>
                {
                    var addr         = args.RemoteAddress.DisplayName;
                    var result       = args.GetDataStream();
                    var resultStream = result.AsStreamForRead(1024);

                    using (var reader = new StreamReader(resultStream))
                    {
                        var resultText = await reader.ReadToEndAsync();

                        if (resultText.StartsWith("HTTP/1.1 200 OK"))
                        {
                            HandleSSDPResponse(resultText);
                        }
                    };
                });
            };

            var ipAddress = PlatformSupport.Services.Network.GetIPV4Address();
            var hostName  = new Windows.Networking.HostName(ipAddress);
            await _readerSocket.BindEndpointAsync(hostName, "");

            Core.PlatformSupport.Services.Logger.AddCustomEvent(LogLevel.Message, "SSDPFinder.QueryAsync", _readerSocket.Information.LocalAddress + " " + _readerSocket.Information.LocalPort);

            _readerSocket.JoinMulticastGroup(remoteIP);

            using (var stream = await _readerSocket.GetOutputStreamAsync(remoteIP, _ssdpPort.ToString()))
            {
                await stream.WriteAsync(reqBuff.AsBuffer());
            }
        }
Ejemplo n.º 7
0
 internal void Close()
 {
     if (_TCPListener != null)
     {
         _TCPListener.Dispose();
     }
     if (_UDPListener != null)
     {
         _UDPListener.Dispose();
     }
 }
Ejemplo n.º 8
0
 async void DisposeSocketAsync()
 {
     if (socket != null)
     {
         socket.Dispose();
     }
 }
Ejemplo n.º 9
0
 protected void CloseSocket()
 {
     DatagramSocket?.Dispose();
     _messageSubscribe?.Dispose();
     InitializeUdpSocket();
     SubsribeToMessages();
 }
Ejemplo n.º 10
0
 public void CheckShutdown()
 {
     // cryptor?.Dispose();
     // cryptor = null;
     // outboundChan = null;
     if (recvData != null)
     {
         ZeroMemory(recvData);
     }
     if (udpClient != null)
     {
         udpClient.MessageReceived -= UdpClient_MessageReceived;
     }
     try
     {
         tcpInputStream?.Dispose();
         udpOutputStream?.Dispose();
     }
     catch (ObjectDisposedException) { }
     // networkStream = null;
     try
     {
         client?.Dispose();
         udpClient?.Dispose();
     }
     catch (ObjectDisposedException) { }
     try
     {
         udpSendLock.Dispose();
     }
     catch (ObjectDisposedException) { }
     // client = null;
     // udpClient = null;
 }
Ejemplo n.º 11
0
 private void OnDestroy()
 {
     if (m_udpSocket != null)
     {
         m_udpSocket.Dispose();
     }
 }
Ejemplo n.º 12
0
        public override async void Stop()
        {
            RaiseStatusChanged(ListenerStatus.NotListening);
            try
            {
                await _semaphoreSlim.WaitAsync();

                try
                {
                    if (_client != null)
                    {
                        _client.Dispose();
                        _client = null;
                    }
                }
                finally
                {
                    _semaphoreSlim.Release();
                }
            }
            catch
            {
                // ignored
            }
        }
Ejemplo n.º 13
0
 public void StopSend()
 {
     try
     {
         if (msocketSend != null)
         {
             //    msocketSend.MessageReceived -= UDPMulticastMessageReceived;
             msocketSend.Dispose();
             msocketSend = null;
         }
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine("Exception while stopping listening: " + e.Message);
     }
 }
Ejemplo n.º 14
0
 //Close socket
 public void Close()
 {
     ClearPeers();
     _datagramSocket.MessageReceived -= OnMessageReceived;
     _datagramSocket.Dispose();
     _datagramSocket = null;
 }
    async void udpMessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
    {
        if (!targetIPReady && !connected && !trashUDP)
        {
            trashUDP = true;
            DataReader reader     = args.GetDataReader();
            uint       len        = reader.UnconsumedBufferLength;
            string     msg        = reader.ReadString(len);
            string     remoteHost = args.RemoteAddress.DisplayName;
            targetIP      = msg;
            targetIPReady = true;
            textOut("" + msg);
            await listenerSocket.CancelIOAsync();

            listenerSocket.MessageReceived -= udpMessageReceived;
            listenerSocket.Dispose();
            listenerSocket = null;//new since working



            //socket.Dispose();

            /* //exception smashing test
             * reader.Dispose();
             *
             * await Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
             * {
             *  targetIP = msg;
             *  targetIPReady = true;
             *  textOut("UDP Set up. "+targetIP+" "+targetIPReady);
             * });
             */
        }
    }
Ejemplo n.º 16
0
        public async Task SendStringData(HostName hostName, string port, string data)
        {
            try
            {
                using (var datagramSocket = new DatagramSocket())
                {
                    await datagramSocket.ConnectAsync(hostName, port);

                    using (Stream outputStream = datagramSocket.OutputStream.AsStreamForWrite())
                    {
                        using (var streamWriter = new StreamWriter(outputStream))
                        {
                            await streamWriter.WriteLineAsync(data);

                            await streamWriter.FlushAsync();
                        }
                    }
                    datagramSocket.Dispose();
                }
            }
            catch (Exception ex)
            {
                SocketErrorStatus webErrorStatus = SocketError.GetStatus(ex.GetBaseException().HResult);
            }
        }
Ejemplo n.º 17
0
        private void _upnpListener_Tick(object sender, object e)
        {
            bool UPnPDiscoveryCompleted = false;

            if (_upnpLastMessageReceived != null)
            {
                if ((DateTime.Now - _upnpDiscoveryStart).TotalSeconds > UPNP_TIMEOUT)
                {
                    UPnPDiscoveryCompleted = true;
                }
            }
            else
            {
                if ((DateTime.Now - _upnpDiscoveryStart).TotalSeconds > UPNP_TIMEOUT)
                {
                    UPnPDiscoveryCompleted = false;
                }
            }

            if (UPnPDiscoveryCompleted)
            {
                _upnpListener.Stop();
                if (_socket != null)
                {
                    _socket.Dispose();
                }
                if (OnUPnPDiscoveryCompleted != null)
                {
                    OnUPnPDiscoveryCompleted(sender, null);
                }
            }
        }
Ejemplo n.º 18
0
        public static async void StopListening()
        {
            await DatagramSocket.CancelIOAsync();

            DatagramSocket.Dispose();
            DatagramSocket = null;
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Stops listening to the socket and closes the thread
 /// </summary>
 public static void StopListening()
 {
     // Close the UDP client
     if (udpSocket != null)
     {
         udpSocket.Dispose();
     }
 }
Ejemplo n.º 20
0
 protected void Close(ref DatagramSocket socket)
 {
     if (socket != null)
     {
         socket.Dispose();
         socket = null;
     }
 }
Ejemplo n.º 21
0
 public void Cleanup()
 {
     try
     {
         tvSearchSocket.Dispose();
     }
     catch { }
 }
Ejemplo n.º 22
0
 internal Task CloseSocketAsync()
 {
     return(Task.Run(() =>
     {
         _backingDatagramSocket.Dispose();
         SetBackingSocket();
     }));
 }
Ejemplo n.º 23
0
 public void TearDownTextSocket()
 {
     if (textMessageSocket != null)
     {
         textMessageSocket.Dispose();
         textMessageSocket = null;
     }
 }
Ejemplo n.º 24
0
 void StopListener()
 {
     if (artnetSocket != null)
     {
         artnetSocket.Dispose();
     }
     artnetSocket = null;
 }
Ejemplo n.º 25
0
 public void Cleanup()
 {
     if (_socketUdp != null)
     {
         _socketUdp.Dispose();
         _socketUdp = null;
     }
 }
Ejemplo n.º 26
0
 public void Dispose()
 {
     if (ServerSocket != null)
     {
         ServerSocket.Dispose();
         ServerSocket = null;
     }
 }
Ejemplo n.º 27
0
        public async Task <Guid> ConnectAsync(HostName hostName, string port)
        {
            if (nameResponse != null)
            {
                throw new InvalidOperationException("The client is connecting to another server");
            }

            nameResponse = new TaskCompletionSource <HClientResponseWithNameAndIP>();

            // Connect to the server
            DatagramSocket socket = new DatagramSocket();

            socket.Control.QualityOfService = SocketQualityOfService.LowLatency;
            socket.MessageReceived         += client_MessageReceived;
            await socket.ConnectAsync(hostName, port);

            // Create new information
            HServerInformation serverInf = new HServerInformation();

            serverInf.Socket    = socket;
            serverInf.Converter = new ShortStreamConverter(socket.OutputStream.AsStreamForWrite());

            // Ping the server
            serverInf.Converter.Write(clientCONNHeader);
            serverInf.Converter.Write(Encoding.UTF8.GetBytes(clientName));
            serverInf.Converter.Flush();

            // Wait for ping (or timeout)
            Task.WhenAny(nameResponse.Task, Task.Delay(CONNECT_TIMEOUT)).Wait();
            if (!nameResponse.Task.IsCompleted)
            {
                nameResponse.TrySetCanceled();
                socket.Dispose();

                Log(serverInf.Guid, "Connection timeout");

                nameResponse = null;

                return(default(Guid));
            }

            // Add new entry
            serverInf.Guid = nameResponse.Task.Result.GUID;
            serverInf.Name = nameResponse.Task.Result.Name;
            serverInf.IP   = nameResponse.Task.Result.IP;
            Log(serverInf.Guid, "Profile added");
            serverList.Add(serverInf);

            nameResponse = null;

            // Fire event
            if (Connected != null)
            {
                Connected(this, serverInf.Guid);
            }

            return(serverInf.Guid);
        }
        public override void Close()
        {
            if (_datagramSocket != null)
            {
                _datagramSocket.Dispose();
            }

            _datagramSocket = null;
        }
Ejemplo n.º 29
0
 private static void ClearPrevious()
 {
     if (socket != null)
     {
         socket.Dispose();
         socket            = null;
         socketIsConnected = false;
     }
 }
Ejemplo n.º 30
0
 /// <summary>Disposes DHCP server</summary>
 internal void Dispose()
 {
     if (socket != null)
     {
         //socket.Close();
         socket.Dispose();
         socket = null;
     }
 }