Пример #1
0
 // Broadcast Message to everyone.
 public void Broadcast(byte[] sendBuffer)
 {
     // Reset.
     if (this.client != null)
     {
         this.client.Close();
         this.client = null;                 // Good Practice?
     }
     try {
         // Open.
         this.client = new UdpClient(new IPEndPoint(IPAddress.Broadcast, this.remotePort));
         // Write.
         this.client.Send(sendBuffer, sendBuffer.Length);
         // Close.
         this.client.Close();
         // Acknowledge.
                         #if DEBUG
         DebugUtilities.UniversalDebug(this.sourceName, "Broadcast Sent!", ref this.debugMessages);
                         #endif
         this.flagSuccess = true;
         return;
     } catch (Exception exception) {
         // Exception.
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                         #endif
     }
 }
Пример #2
0
 // Broadcast Message to everyone.
 public async void Broadcast(byte[] sendBuffer)
 {
     // Reset.
     if (this.client != null)
     {
         this.client.Dispose();
         this.client = null;                 // Good Practice?
     }
     try {
         // Open.
         this.client = new DatagramSocket();
         // Write.
         using (var stream = await this.client.GetOutputStreamAsync(new HostName(UDPSend.broadcastAddress),
                                                                    this.remotePort.ToString())) {
             using (DataWriter writer = new DataWriter(stream)) {
                 writer.WriteBytes(sendBuffer);
                 await writer.StoreAsync();
             }
         }
         // Close.
         this.client.Dispose();
         // Acknowledge.
                         #if DEBUG
         DebugUtilities.UniversalDebug(this.sourceName, "Broadcast Sent!", ref this.debugMessages);
                         #endif
         this.flagSuccess = true;
         return;
     } catch (Exception exception) {
         // Exception.
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                         #endif
     }
 }
Пример #3
0
 ////////////////////////////////////////////////////////////////////////
 // Start a connection and send given byte array.
 private async void Send(byte[] sendBuffer)
 {
     this.flagSuccess = false;
     // Reset.
     if (this.client != null)
     {
         this.client.Close();
         this.client = null;                 // Good Practice?
     }
     try {
         // Open.
         this.client = new UdpClient(this.remoteIP, this.remotePort);
         // Write.
         this.client.Send(sendBuffer, sendBuffer.Length);
         // Close.
         this.client.Close();
         // Acknowledge.
                         #if DEBUG
         DebugUtilities.UniversalDebug(this.sourceName, "Data Sent!", ref this.debugMessages);
                         #endif
         this.flagSuccess = true;
         return;
     } catch (Exception exception) {
         // Exception.
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                         #endif
     }
 }
Пример #4
0
        ////////////////////////////////////////////////////////////////////////
        // Establish Connection
        public async void Connect()
        {
            // Reset.
            Disconnect();
            this.client = new StreamSocket();
            this.connectionCancellationTokenSource = new CancellationTokenSource();
            this.sendCancellationTokenSource       = new CancellationTokenSource();
            this.flagConnected = false;
            try {
                this.connectionCancellationTokenSource.CancelAfter(this.timeout);
                await this.client.ConnectAsync(new HostName(this.remoteIP), this.remotePort.ToString())
                .AsTask(this.connectionCancellationTokenSource.Token);

                StartSending();
                this.flagConnected = true;
                // Acknowledge.
                                #if DEBUG
                DebugUtilities.UniversalDebug(this.sourceName, "Connection Stablished!", ref this.debugMessages);
                                #endif
                // return true;
            } catch (TaskCanceledException) {
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Failed to connect", ref this.debugMessages);
                                #endif
            } catch (Exception exception) {
                SocketErrorStatus webErrorStatus = SocketError.GetStatus(exception.GetBaseException().HResult);
                string            errorMessage   = (webErrorStatus.ToString() != "Unknown") ? webErrorStatus.ToString() : exception.Message;
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "UnhandledException: " + errorMessage, ref this.debugMessages);
                                #endif
                // return false;
            }
        }
Пример #5
0
        // Constantly check for new messages on given port.
        private void ReceiveData()
        {
            // Open.
            this.client = new UdpClient(this.localPort);
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);

            // Infinite loop.
            try {
                byte[] data;
                string receiveString;
                while (true)
                {
                    // Receive Bytes.
                    data = client.Receive(ref anyIP);
                    if (data.Length > 0)
                    {
                        // If buffer not empty - decode it.
                        receiveString = EncodeUtilities.DecodeData(data);
                        // If string not empty and not read yet - react to it.
                        if (!string.IsNullOrEmpty(receiveString))
                        {
                                                        #if DEBUG2
                            DebugUtilities.UniversalDebug(this.sourceName, "Total Data found: " + receiveString, ref this.debugMessages);
                                                        #endif
                            if ((this.dataMessages.Count == 0) ||
                                (this.flagForce || (this.dataMessages[this.dataMessages.Count - 1] != receiveString)))
                            {
                                this.dataMessages.Add(receiveString);
                                this.connectionHistory.Add(anyIP.Address.ToString());
                                this.flagDataRead = false;
                                if (OnReceive != null)
                                {
                                    OnReceive();
                                }
                            }
                            else
                            {
                                                                #if DEBUG2
                                DebugUtilities.UniversalDebug(this.sourceName, "Message already added.", ref this.debugMessages);
                                                                #endif
                            }
                        }
                    }
                }
            } catch (SocketException exception) {
                // SocketException.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "SocketException: " + exception.ToString(), ref this.debugMessages);
                                #endif
            } catch (Exception exception) {
                // Exception.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                                #endif
            } finally {
                this.Disconnect();
            }
        }
Пример #6
0
        private async void OnClientFound(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            this.flagConnectionFound = true;
                        #if DEBUG
            DebugUtilities.UniversalDebug(this.sourceName, "New Client Found!", ref this.debugMessages);
                        #endif
            uint dataLengthToRead;

            this.reader = new DataReader(args.Socket.InputStream);
            this.reader.InputStreamOptions = InputStreamOptions.Partial;
            this.reader.UnicodeEncoding    = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                        #if DEBUG
            DebugUtilities.UniversalDebug(this.sourceName, "Starting infinite loop reading data.", ref this.debugMessages);
                        #endif
            try {
                while (true)
                {
                    // Try to read a byte - if timed out - will raise an exceptiion.
                    // CancellationTokenSource timeoutSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000));
                    // uint temp = await this.reader.LoadAsync(1).AsTask(timeoutSource.Token);

                    dataLengthToRead = await this.reader.LoadAsync(this.bufferSize);

                    if ((dataLengthToRead != 0) && (!this.currentHistory.Contains(EncodeUtilities.messageSplitter)))
                    {
                                                #if DEBUG2
                        DebugUtilities.UniversalDebug(this.sourceName, "Data found in stream.", ref this.debugMessages);
                                                #endif
                        this.currentHistory += this.reader.ReadString(dataLengthToRead);
                        // Check if there is more data in stream.
                        dataLengthToRead = await this.reader.LoadAsync(bufferSize);
                    }
                    // if found a message splitter - process first and remove from history.
                    if (this.currentHistory.Contains(EncodeUtilities.messageSplitter))
                    {
                        ReactToMessage();
                    }
                    // await Task.Delay(TimeSpan.FromMilliseconds(100));
                    // DebugUniversal("Keeping going . . .");
                }
            } catch (TaskCanceledException) {
                // timeout
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Connection timed out!", ref this.debugMessages);
                                #endif
            } catch (Exception exception) {
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Receiving Exception: " + exception.ToString(), ref this.debugMessages);
                                #endif
            }
            // TODO: Shouldn't it close in case of error?
            // finally {
            //  this.flagConnectionFound = false;
            //  this.reader.DetachStream();
            // }
        }
 /////////////////////////////////////////////////////////////////////////////
 // A function responsible for decoding and reacting to received UDP data.
 private bool InterpreteData(string message)
 {
     if (!string.IsNullOrEmpty(message))
     {
         message = EncodeUtilities.StripSplitter(message);
         if (this.lastMessage != message)
         {
             this.lastMessage = message;
                                 #if DEBUG
             DebugUtilities.UniversalDebug(this.sourceName, "New message found: " + message);
                                 #endif
             string[] messageComponents = message.Split(new string[] { EncodeUtilities.headerSplitter }, 2, StringSplitOptions.RemoveEmptyEntries);
             if (messageComponents.Length > 1)
             {
                 string header = messageComponents[0], content = messageComponents[1];
                                         #if DEBUG
                 DebugUtilities.UniversalDebug(this.sourceName, "Header: " + header + ", content: " + content);
                                         #endif
                 if (header == "MESHSTREAMING")
                 {
                     InterpreteMesh(content, SourceType.UDP);
                     return(true);
                 }
                 else if (header == "CONTROLLER")
                 {
                     InterpreteRobotController(content);
                     return(true);
                 }
                 else if (header == "HOLOTAG")
                 {
                     InterpreteTag(content);
                     return(true);
                 }
                 else if (header == "IPADDRESS")
                 {
                     InterpreteIPAddress(content);
                     return(true);
                 }
                 else
                 {
                                                 #if DEBUGWARNING
                     DebugUtilities.UniversalWarning(this.sourceName, "Header Not Recognized");
                                                 #endif
                 }
             }
             else
             {
                                         #if DEBUGWARNING
                 DebugUtilities.UniversalWarning(this.sourceName, "Improper message");
                                         #endif
             }
         }
     }
     return(true);           // Since we have one interpreter anyway
 }
Пример #8
0
 //////////////////////////////////////////////////////////////////////////
         #if WINDOWS_UWP
 private async void StartReceiving()
 {
     // Reset.
     // Start receiving.
     this.client = new DatagramSocket();
     this.client.MessageReceived += ReceiveData;
     try {
         await client.BindEndpointAsync(new HostName(NetworkUtilities.LocalIPAddress()), this.localPort.ToString());
     } catch (Exception exception) {
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString() + ":" + SocketError.GetStatus(exception.HResult).ToString(), ref this.debugMessages);
                         #endif
     }
                 #if DEBUG
     DebugUtilities.UniversalDebug(this.sourceName, "Client receivng thread Started.", ref this.debugMessages);
                 #endif
 }
Пример #9
0
 ////////////////////////////////////////////////////////////////////////
 // Establish Connection
 public bool Connect()
 {
     // Reset.
     Disconnect();
     this.client        = new TcpClient();
     this.flagConnected = false;
     try {
         // Open.
         if (!this.client.ConnectAsync(this.remoteIP, this.remotePort).Wait(this.timeout))
         {
             // connection failure
                                 #if DEBUGWARNING
             DebugUtilities.UniversalWarning(this.sourceName, "Failed to connect", ref this.debugMessages);
                                 #endif
             return(false);
         }
         this.stream        = this.client.GetStream();
         this.flagConnected = true;
         StartSending();
         // Acknowledge.
                         #if DEBUG
         DebugUtilities.UniversalDebug(this.sourceName, "Connection Stablished!", ref this.debugMessages);
                         #endif
         return(true);
     } catch (ArgumentNullException exception) {
         // Exception.
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "ArgumentNullException: " + exception.ToString(), ref this.debugMessages);
                         #endif
         return(false);
     } catch (SocketException exception) {
         // Exception.
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "SocketException: " + exception.ToString(), ref this.debugMessages);
                         #endif
         return(false);
     } catch (Exception exception) {
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "UnhandledException: " + exception.ToString(), ref this.debugMessages);
                         #endif
         return(false);
     }
 }
Пример #10
0
        // Constantly check for new messages on given port.
        private async void ReceiveConnection()
        {
            try {
                // Open.
                this.listener = new StreamSocketListener();
                this.listener.ConnectionReceived += OnClientFound;
                await this.listener.BindServiceNameAsync(this.localPort.ToString());

                                #if DEBUG
                DebugUtilities.UniversalDebug(this.sourceName, "Started Listening for Incoming Connections.", ref this.debugMessages);
                                #endif
            } catch (Exception exception) {
                // Exception.
                SocketErrorStatus webErrorStatus = SocketError.GetStatus(exception.GetBaseException().HResult);
                string            webError       = (webErrorStatus.ToString() != "Unknown") ? webErrorStatus.ToString() :
                                                   exception.Message;
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + webError, ref this.debugMessages);
                                #endif
            }
        }
Пример #11
0
 // Check the queue and try send it.
 public void SendFromQueue()
 {
     try {
         if (this.IsNotEmpty)
         {
             byte[] currentData;
             lock (this.sendQueue)
                 currentData = this.sendQueue.Dequeue();
             // Peek message to send
             Send(currentData);
             // if no exception caught and data sent successfully - remove from queue.
             // if (!this.flagSuccess)
             //  lock (this.sendQueue)
             //      this.sendQueue.Dequeue(currentData);
         }
     } catch (Exception exception) {
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "Queue Exception: " + exception.ToString(), ref this.debugMessages);
                         #endif
     }
 }
Пример #12
0
        // Constantly check for new messages on given port.
        private void ReceiveData()
        {
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);

            byte[] data;
            string receiveString;

            try {
                // Receive Bytes.
                data = this.client.Receive(ref anyIP);
                if (data.Length > 0)
                {
                    // If buffer not empty - decode it.
                    receiveString = EncodeUtilities.DecodeData(data);
                    // If string not empty and not read yet - react to it.
                    if (!string.IsNullOrEmpty(receiveString))
                    {
                                                #if DEBUG2
                        DebugUtilities.UniversalDebug(this.sourceName, "Total Data found: " + receiveString, ref this.debugMessages);
                                                #endif
                        this.dataMessages.Enqueue(receiveString);
                        this.connectionHistory.Enqueue(anyIP.Address.ToString());
                        if (OnReceive != null)
                        {
                            OnReceive();
                        }
                    }
                }
            } catch (SocketException exception) {
                // SocketException.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "SocketException: " + exception.ToString(), ref this.debugMessages);
                                #endif
            } catch (Exception exception) {
                // Exception.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                                #endif
            }
        }
Пример #13
0
 public void SendUI(byte[] data)
 {
     if (!string.IsNullOrEmpty(this.remoteIP))              // just in case
     {
         if ((this.udpSender == null) || (this.udpSender.remoteIP != this.remoteIP))
         {
             this.udpSender = new UDPSend(this.remoteIP, this.remotePortOverride);
             this.udpSender.Connect();
         }
         this.udpSender.QueueUpData(data);
         // if (!this.udpSender.success) {
         //  #if DEBUGWARNING
         //  DebugUtilities.UniversalWarning(this.sourceName, "Couldn't send data.");
         //  #endif
         // }
     }
     else
     {
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "No server IP Found - enable Grasshopper UI Receiving Component");
                         #endif
     }
 }
Пример #14
0
        // Start a connection and send given byte array.
        private void Send(byte[] sendBuffer)
        {
            this.flagSuccess = false;
            try {
                if (!this.client.Connected)
                {
                                        #if DEBUGWARNING
                    DebugUtilities.UniversalWarning(this.sourceName, "Client Disconnected!", ref this.debugMessages);
                                        #endif
                    return;
                }

                // Write.
                this.stream.Write(sendBuffer, 0, sendBuffer.Length);
                // Acknowledge.
                                #if DEBUG
                DebugUtilities.UniversalDebug(this.sourceName, "Data Sent!", ref this.debugMessages);
                                #endif
                this.flagSuccess = true;
            } catch (ArgumentNullException exception) {
                // Exception.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "ArgumentNullException: " + exception.ToString(), ref this.debugMessages);
                                #endif
            } catch (SocketException exception) {
                // Exception.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "SocketException: " + exception.ToString(), ref this.debugMessages);
                                #endif
            } catch (Exception exception) {
                // Exception.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                                #endif
            }
        }
Пример #15
0
 // Start a connection and send given byte array.
 public async void Send(byte[] sendBuffer)
 {
     this.flagSuccess = false;
     try {
         if ((this.client != null) && this.flagConnected)
         {
             // Write.
             using (Stream outputStream = this.client.OutputStream.AsStreamForWrite()) {
                 await outputStream.WriteAsync(sendBuffer, 0, sendBuffer.Length, this.sendCancellationTokenSource.Token);
             }
             // Acknowledge.
                                 #if DEBUG
             DebugUtilities.UniversalDebug(this.sourceName, "Data Sent!", ref this.debugMessages);
                                 #endif
             this.flagSuccess = true;
         }
         else
         {
                                 #if DEBUGWARNING
             DebugUtilities.UniversalWarning(this.sourceName, "Not connected", ref this.debugMessages);
                                 #endif
             this.flagConnected = false;
         }
     } catch (TaskCanceledException) {
         // timeout
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "Connection timed out!", ref this.debugMessages);
                         #endif
         this.flagConnected = false;
     } catch (Exception exception) {
         // Exception.
                         #if DEBUGWARNING
         DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                         #endif
     }
 }
Пример #16
0
        // Constantly check for new messages on given port.
        private void ReceiveData()
        {
            try {
                // Open.
                IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, this.localPort);
                this.listener = new TcpListener(anyIP);
                this.listener.Start();

                this.currentHistory = "";
                // Infinite loop.
                while (true)
                {
                    if (this.client == null)
                    {
                                                #if DEBUG
                        DebugUtilities.UniversalDebug(this.sourceName, "Listening for a Client!", ref this.debugMessages);
                                                #endif
                        this.client = this.listener.AcceptTcpClient();
                        this.stream = this.client.GetStream();
                    }
                    else
                    {
                        try {
                            if (this.stream.DataAvailable)
                            {
                                OnClientFound();
                                                                #if DEBUG
                                DebugUtilities.UniversalDebug(this.sourceName, "Reading Data: " + this.client.Available.ToString(), ref this.debugMessages);
                                                                #endif
                            }
                            else
                            {
                                if (this.IsConnected)
                                {
                                                                        #if DEBUGWARNING
                                    DebugUtilities.UniversalWarning(this.sourceName, "No Data Available!", ref this.debugMessages);
                                                                        #endif
                                }
                                else
                                {
                                                                        #if DEBUGWARNING
                                    DebugUtilities.UniversalWarning(this.sourceName, "Client Disconnected", ref this.debugMessages);
                                                                        #endif
                                    this.stream.Close();
                                    this.client.Close();
                                    this.client = null;
                                }
                            }
                        } catch (Exception e) {
                            this.stream.Close();
                            this.client.Close();
                            this.client = null;
                        }
                    }
                }
            } catch (SocketException exception) {
                // SocketException.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "SocketException: " + exception.ToString(), ref this.debugMessages);
                                #endif
            } catch (Exception exception) {
                // Exception.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                                #endif
            }
            // TODO: Shouldn't it close in case of error?
            // finally {
            //  this.Disconnect();
            // }
        }