GetDataReader() public method

public GetDataReader ( ) : DataReader
return Windows.Storage.Streams.DataReader
Exemplo n.º 1
0
        //private void DataReceived(object o)
        private void DataSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                var reader = args.GetDataReader();

                byte[] data = new byte[reader.UnconsumedBufferLength];
                args.GetDataReader().ReadBytes(data);

                this.socket = sender;

                var dhcpRequest = new DHCPRequest(data, socket, this);
                //ccDHCP = new clsDHCP();


                //data is now in the structure
                //get the msg type
                OnDataReceived(this, dhcpRequest);
                var msgType = dhcpRequest.GetMsgType();
                switch (msgType)
                {
                case DHCPMsgType.DHCPDISCOVER:
                    OnDiscover(this, dhcpRequest);
                    break;

                case DHCPMsgType.DHCPREQUEST:
                    OnRequest(this, dhcpRequest);
                    break;

                case DHCPMsgType.DHCPDECLINE:
                    OnDecline(this, dhcpRequest);
                    break;

                case DHCPMsgType.DHCPRELEASE:
                    OnReleased(this, dhcpRequest);
                    break;

                case DHCPMsgType.DHCPINFORM:
                    OnInform(this, dhcpRequest);
                    break;
                    //default:
                    //    Console.WriteLine("Unknown DHCP message: " + (int)MsgTyp + " (" + MsgTyp.ToString() + ")");
                    //    break;
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                {
                    UnhandledException(this, ex);
                }
            }
        }
        void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            DataReader dr = args.GetDataReader();
            var dataLength = dr.UnconsumedBufferLength;

            string discoveryResult = dr.ReadString(dataLength);
            string[] parts = discoveryResult.Split('|');
            string name = parts[0];
            bool isPinProtected = bool.Parse(parts[1]);
            string uniqueName = parts[3];

            var existingTarget = GetShareTarget(uniqueName);

            var discoveredTarget = new ShareTarget()
            {
                Name = name,
                IPAddress = args.RemoteAddress.DisplayName,
                IsPinCodeRequired = isPinProtected,
                ShareTargetUniqueName = uniqueName
            };

            if (existingTarget != null)
            {
                discoveredTarget.ShareCount = existingTarget.ShareCount;
            }

            if (PeerDiscovered != null)
            {
                PeerDiscovered(discoveredTarget);
            }
        }
Exemplo n.º 3
0
        async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            i++;
            DataReader dataReader = args.GetDataReader();
            uint length = dataReader.UnconsumedBufferLength;
            string content = dataReader.ReadString(length);
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            msgList.Children.Add(new TextBlock { Text = "服务器收到的消息:" + content }));

            //HostName hostName = new HostName("localhost");
            //DatagramSocket datagramSocket = new DatagramSocket();
            //IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, "22112");
            DataWriter writer = new DataWriter(sender.OutputStream);
            writer.WriteString(content + "|" + i);
            try
            {
                await writer.StoreAsync();
                msgList.Children.Add(new TextBlock { Text = "服务器发送的消息:" + content + "|" + i });
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {

                }
            }
        }
Exemplo n.º 4
0
        private void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            DataReader reader;
            try
            {
                reader = eventArguments.GetDataReader();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("MessageReceived:" + ex);
                return;
            }
            uint dataLength = reader.UnconsumedBufferLength;
            byte[] data = new byte[dataLength];
            reader.ReadBytes(data);

            var packet = new NavigationPacket
            {
                Timestamp = DateTime.UtcNow.Ticks,
                Data = data
            };
            UpdateNavigationData(packet);

            _TimeoutStopWatch.Restart();
        }
 private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     var dataReader = args.GetDataReader();
     var length = dataReader.UnconsumedBufferLength;
     var message = dataReader.ReadString(length);
     var guidAsString = message.Replace("TT_DEVICE_IDENTIFIER:", "").Trim();
     _deviceFoundCallback?.Invoke(new TickTackHub { Id = guidAsString });
 }
Exemplo n.º 6
0
 void datagramSocket_MessageReceived2(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     i++;
     DataReader dataReader = args.GetDataReader();
     uint length = dataReader.UnconsumedBufferLength;
     string content = dataReader.ReadString(length);
     Deployment.Current.Dispatcher.BeginInvoke(() =>
    msgList.Children.Add(new TextBlock { Text = "客户端收到的消息:" + content }));
 }
Exemplo n.º 7
0
        private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            uint stringLength = args.GetDataReader().UnconsumedBufferLength;
            byte[] result = new byte[args.GetDataReader().UnconsumedBufferLength];
            args.GetDataReader().ReadBytes(result);

            OSCPacket message = OSCPacket.Unpack(result);

            //var result = args.GetDataStream();
            //var resultStream = result.AsStreamForRead(1024);

            //using (var reader = new StreamReader(resultStream))
            //{
            //    var text = await reader.ReadToEndAsync();
                
                //CoreWindow.GetForCurrentThread().Dispatcher
            //}
        }
Exemplo n.º 8
0
        private static void DatagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            using (DataReader reader = args.GetDataReader())
            {
                byte[] b = new byte[48];

                reader.ReadBytes(b);

                App.NtpTimeOffset = GetNetworkTime(b) - DateTime.UtcNow;
            }
        }
Exemplo n.º 9
0
        private async void ServerDatagramSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            string request;

            using (DataReader dataReader = args.GetDataReader())
            {
                request = dataReader.ReadString(dataReader.UnconsumedBufferLength).Trim();
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add(string.Format("server received the request: \"{0}\"", request)));
        }
Exemplo n.º 10
0
        private async void OnMessageReceived(
            DatagramSocket sender,
            DatagramSocketMessageReceivedEventArgs args)
        {
            var senderHostname = new HostName(args.RemoteAddress.RawName);

            var writer = new DataWriter(await sender.GetOutputStreamAsync(senderHostname, args.RemotePort));

            var stream = new NetworkStream(args.GetDataReader(), writer);

            this.clients.ForEach(x => x.MessageReceived(this, stream));
        }
Exemplo n.º 11
0
        static void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            using (DataReader reader = args.GetDataReader())
            {
                byte[] b = new byte[48];

                reader.ReadBytes(b);

                DateTime time = Util.GetNetworkTime(b);
                utcOffset = DateTime.UtcNow.Subtract(time);
            }
        }
Exemplo n.º 12
0
		static async void multicastSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs eventArguments) {
			try {
				HostName remoteHostAddress = eventArguments.RemoteAddress;
				uint len = eventArguments.GetDataReader().UnconsumedBufferLength;
				string message = eventArguments.GetDataReader().ReadString(len).Trim();
				int p = message.IndexOf(':');
				if (p != -1) {
					string serverLogToken = message.Substring(0, p);
					int port = Int32.Parse(message.Substring(p + 1));

					if (serverLogToken == logToken && port > 0 && port < 65535) {
						Debug.WriteLine("[LOGGER] Found a Titanium log server: " + remoteHostAddress.DisplayName + ":" + port);

						try {
							tcpSocket = new StreamSocket();
							tcpSocket.Control.KeepAlive = true;
							await tcpSocket.ConnectAsync(remoteHostAddress, port.ToString());
							tcpWriter = new DataWriter(tcpSocket.OutputStream);

							// shutdown the multicast socket and start the tcp connection
							multicastSocket.Dispose();
						} catch {
							if (tcpWriter != null) {
								tcpWriter.Dispose();
								tcpWriter = null;
							}
							if (tcpSocket != null) {
								tcpSocket.Dispose();
								tcpSocket = null;
							}
						}
					}
				}
			} catch (Exception ex) {
				if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) {
					throw;
				}
				Debug.WriteLine(ex.ToString());
			}
		}
        /// <summary>
        /// MessageReceived event
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="eventArguments"></param>
          void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            try
            {
                //get string length
                uint stringLength = eventArguments.GetDataReader().UnconsumedBufferLength;
                 
                    //read string from the stream
                    string receivedMessage = eventArguments.GetDataReader().ReadString(stringLength);

                    //it is not possible to access controls from here
                    var ignore = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    do_job(eventArguments.RemoteAddress.ToString(), receivedMessage, eventArguments.RemotePort.ToString(),
                    eventArguments.LocalAddress.ToString()));
                
            }
            catch (Exception ex)
            {
                //show exception on the Network Log textbox
                bytes_s.Content = ex.ToString(); 
            }
        }
        private async void _socket_OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs e)
        {
            var reader = e.GetDataReader();
            string message = reader.ReadString(reader.UnconsumedBufferLength);

            Logger.Trace("Message from {0}:{1}:\n{2}", e.RemoteAddress.RawName, e.RemotePort, message);

            IOutputStream outputStream = await sender.GetOutputStreamAsync(e.RemoteAddress, e.RemotePort);
            Received(this, new PeerCommandEventArgs
                               {
                                   Data = message,
                                   Peer = new RemotePeer(_serializer, this, outputStream, e.RemoteAddress, e.RemotePort),
                               });
        }
Exemplo n.º 15
0
 private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     try
     {
         using (var reader = args.GetDataReader())
         {
             byte[] response = new byte[48];
             reader.ReadBytes(response);
             _resultCompletionSource.TrySetResult(ParseNetworkTime(response));
         }
     }
     catch (Exception ex)
     {
         _resultCompletionSource.TrySetException(ex);
     }
 }
Exemplo n.º 16
0
        private void DatagramSocketOnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                var dataReader = args.GetDataReader();
                var receiveBytes = new byte[dataReader.UnconsumedBufferLength];
                dataReader.ReadBytes(receiveBytes);
                var receiveString = Encoding.ASCII.GetString(receiveBytes);
                var exp = new Regex(
                    "BT-SEARCH \\* HTTP/1.1\\r\\nHost: 239.192.152.143:6771\\r\\nPort: (?<port>[^@]+)\\r\\nInfohash: (?<hash>[^@]+)\\r\\n\\r\\n\\r\\n");
                var match = exp.Match(receiveString);

                if (!match.Success)
                    return;

                var portcheck = Convert.ToInt32(match.Groups["port"].Value);
                if (portcheck < 0 || portcheck > 65535)
                    return;

                TorrentManager manager = null;
                var matchHash = InfoHash.FromHex(match.Groups["hash"].Value);
                for (var i = 0; manager == null && i < _engine.Torrents.Count; i++)
                    if (_engine.Torrents[i].InfoHash == matchHash)
                        manager = _engine.Torrents[i];

                if (manager == null)
                    return;

                var uri = new Uri("tcp://" + args.RemoteAddress.RawName + ':' + match.Groups["port"].Value);
                var peer = new Peer("", uri, EncryptionTypes.All);

                // Add new peer to matched Torrent
                if (manager.HasMetadata && manager.Torrent.IsPrivate)
                    return;
                ClientEngine.MainLoop.Queue(delegate
                {
                    var count = manager.AddPeersCore(peer);
                    manager.RaisePeersFound(new LocalPeersAdded(manager, count, 1));
                });
            }
            catch
            {
                // ignored
            }
        }
Exemplo n.º 17
0
 private void TrackerOnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     if (_taskCompletionSource == null || _taskCompletionSource.Task.IsCompleted)
         return;
     try
     {
         var dataReader = args.GetDataReader();
         var result = new byte[dataReader.UnconsumedBufferLength];
         dataReader.ReadBytes(result);
         _taskCompletionSource.SetResult(result);
     }
     catch (Exception ex)
     {
         lock (_lock)
             _timeout = 0;
         _taskCompletionSource.TrySetException(ex);
     }
 }
Exemplo n.º 18
0
        private void MessageReceivedCallback(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            try
            {
                // Save message received from server.
                DataReader dataReader = eventArguments.GetDataReader();
                uint length = dataReader.UnconsumedBufferLength;
                m_message = dataReader.ReadString(length);
            }
            catch (Exception exception)
            {

            }
            
            if (m_callbackFunction != null)
            {
                m_callbackFunction(m_message);
            }
        }
Exemplo n.º 19
0
        private void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                DataReader reader = args.GetDataReader();
                reader.InputStreamOptions = InputStreamOptions.Partial;
                uint bytesRead = reader.UnconsumedBufferLength;
                String message = reader.ReadString(bytesRead);

                playPage.DisplayMessages(name + " :Message received [" +
                    args.RemoteAddress.DisplayName.ToString() + "]:" + args.RemotePort + ": " + message);

                SendMessage(IPAdress.LocalIPAddress() + " " + name, args.RemoteAddress.DisplayName.ToString(), portSender);
                reader.Dispose();
            }
            catch (Exception ex)
            {
                playPage.DisplayMessages(name + " :ERROR: Message received from:\n" + ex.ToString());
            }
        }
Exemplo n.º 20
0
        private void Socket_Completed_Receive(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                ExecuteWithSuppressedExceptions(() => sender.MessageReceived -= this.Socket_Completed_Receive);

                byte[] buffer = null;
                using (var reader = args.GetDataReader())
                {
                    buffer = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(buffer);
                }

                ConvertBufferToCurrentTime(buffer);
            }
            catch (Exception ex)
            {
                OnErrorOccurred(ExceptionToNtpNetworkException(ex));
            }
        }
Exemplo n.º 21
0
        private void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
        {
            playPage.DisplayMessages(name + " :MessageReceived");
            try
            {
                DataReader reader = args.GetDataReader();
                reader.InputStreamOptions = InputStreamOptions.Partial;
                uint bytesRead = reader.UnconsumedBufferLength;
                string message = reader.ReadString(bytesRead);
                string msg = message.Replace("\0", string.Empty);
                playPage.DisplayMessages(name + " :Message received from [" +
                    args.RemoteAddress.DisplayName.ToString() + "]:" + args.RemotePort + ": " + message);

                reader.Dispose();
                playPage.AddServer(msg);
            }
            catch (Exception ex)
            {
                playPage.DisplayMessages(name + " :ERROR: Message received from:" + ex.ToString());
            }
        }
Exemplo n.º 22
0
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                  Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            // lock multi event
            socket.MessageReceived -= Socket_MessageReceived;

            //Debug.Log("OSCSERVER UWP  Socket_MessageReceived");

            //Read the message that was received from the UDP echo client.
            //Stream streamIn = args.GetDataStream().AsStreamForRead();
            DataReader reader = args.GetDataReader();

            //StreamReader reader = new StreamReader(streamIn);
            try
            {
                uint   stringLength = reader.UnconsumedBufferLength;
                byte[] bytes        = new byte[stringLength];
                reader.ReadBytes(bytes);

                //string message = await reader.ReadToEndAsync()
                //                 .ConfigureAwait(continueOnCapturedContext: false);
                //byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);

                OSCPacket packet = OSCPacket.Unpack(bytes);
                _lastReceivedPacket = packet;

                PacketReceivedEvent(this, _lastReceivedPacket);
            }
            catch (System.Exception e)
            {
                WorldErrors.Print(e.Message);
            }
            finally
            {
                //streamIn.Dispose();
                reader.Dispose();
                // unlock multi event
                socket.MessageReceived += Socket_MessageReceived;
            }
        }
Exemplo n.º 23
0
            private void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
            {
                //Logger.Trace("OnMessageReceived: endpoint = {0}, port = {1}", args.RemoteAddress, args.RemotePort);

                var reader = args.GetDataReader();
                var count = reader.UnconsumedBufferLength;
                var data = new byte[count];
                reader.ReadBytes(data);
                lock (m_messages)
                {
                    m_messages.Add(new Message { Data = data });
                }
                m_messageReceivedEvent.Set();
            }
Exemplo n.º 24
0
 private void Sock_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     using (DataReader reader = args.GetDataReader())
     {
         string value = reader.ReadString(reader.UnconsumedBufferLength);
         switch (value.Trim())
         {
             case "create":
                 car = new SmartCar();
                 break;
             case "forward":
                 if (car != null)
                 {
                     car.FowardBackword(Direction.Forward);
                 }
                 break;
             case "backward":
                 if (car != null)
                 {
                     car.FowardBackword(Direction.Backward);
                 }
                 break;
             case "turnright":
                 if (car != null)
                 {
                     car.TurnRight();
                 }
                 break;
             case "turnleft":
                 if (car != null)
                 {
                     car.TurnLeft();
                 }
                 break;
             case "backright":
                 if (car != null)
                 {
                     car.TurnBackwardRight();
                 }
                 break;
             case "backleft":
                 if (car != null)
                 {
                     car.TurnBackwardLeft();
                 }
                 break;
             case "stop":
                 if (car != null)
                 {
                     car.Stop();
                 }
                 break;
             case "speed":
                 if (car != null)
                 {
                     car.SpeedTest();
                 }
                 break;
         }
     }
 }
 void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
 {
     try
     {
         // Interpret the incoming datagram's entire contents as a string.
         uint stringLength = eventArguments.GetDataReader().UnconsumedBufferLength;
         string receivedMessage = eventArguments.GetDataReader().ReadString(stringLength);
         
         NotifyUserFromAsyncThread(
             "Received data from remote peer: \"" +
             receivedMessage + "\"", 
             NotifyType.StatusMessage);
     }
     catch (Exception exception)
     {
         SocketErrorStatus socketError = SocketError.GetStatus(exception.HResult);
         if (socketError == SocketErrorStatus.ConnectionResetByPeer)
         {
             // This error would indicate that a previous send operation resulted in an 
             // ICMP "Port Unreachable" message.
             NotifyUserFromAsyncThread(
                 "Peer does not listen on the specific port. Please make sure that you run step 1 first " +
                 "or you have a server properly working on a remote server.", 
                 NotifyType.ErrorMessage);
         }
         else if (socketError != SocketErrorStatus.Unknown)
         {
             NotifyUserFromAsyncThread(
                 "Error happened when receiving a datagram: " + socketError.ToString(), 
                 NotifyType.ErrorMessage);
         }
         else
         {
             throw;
         }
     }
 }
Exemplo n.º 26
0
        async void EchoMessage(RemotePeer peer, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            if (!peer.IsMatching(eventArguments.RemoteAddress, eventArguments.RemotePort))
            {
                // In the sample we are communicating with just one peer. To communicate with multiple peers application
                // should cache output streams (i.e. by using a hash map), because creating an output stream for each
                //  received datagram is costly. Keep in mind though, that every cache requires logic to remove old
                // or unused elements; otherwise cache turns into a memory leaking structure.
                //NotifyUserFromAsyncThread(String.Format("Got datagram from {0}:{1}, but already 'connected' to {3}", eventArguments.RemoteAddress, eventArguments.RemotePort, peer), NotifyType.ErrorMessage);
            }

            try
            {
                var reader = eventArguments.GetDataReader();
                var size = reader.UnconsumedBufferLength;
                StringBuilder sb = new StringBuilder();
                while (reader.UnconsumedBufferLength > 0)
                {
                    var b = reader.ReadByte();
                    sb.Append((char) b);
                }

                var msg = sb.ToString();

                if (msg.StartsWith("VS:"))
                {
                    msg = msg.Substring(3);
                    var colon = msg.IndexOf(':');
                    var typename = msg.Substring(0, colon);
                    var equals = msg.IndexOf('=');
                    var ip = msg.Substring(colon + 1, equals - colon - 1);
                    var name = msg.Substring(equals + 1);
                    var colon2 = name.IndexOf(':');

                    if (colon2 > -1)
                    {
                        name = name.Substring(0, colon2);
                    }

                    if (string.IsNullOrWhiteSpace(name))
                    {
                        name = $"({typename}):{ip}";
                    }

                    var port = peer.Port;
                    var portColon = ip.IndexOf(':');
                    if (portColon > -1)
                    {
                        port = ip.Substring(portColon + 1);
                        ip = ip.Substring(0, portColon);
                    }

                    peer.IP = ip;
                    peer.Name = name;
                    peer.Message = msg;
                    peer.Pinged = DateTime.Now;
                    peer.OriginalPort = peer.Port;
                    peer.Port = port;

                    var connection = new Connection(name, peer);
                    if (!clients.ContainsKey(ip))
                    {
                        clients[ip] = connection;
                    }
                }
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
            }
        }
Exemplo n.º 27
0
        private void OnMessageReceived(
            DatagramSocket sender,
            DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                DataReader reader = args.GetDataReader();
                reader.InputStreamOptions = InputStreamOptions.Partial;

                // LoadAsync not needed. The reader comes already loaded.

                // If called by a 'Udp send socket', next line throws an exception because message was not received.

                // If remote peer didn't received message, "An existing connection was forcibly
                // closed by the remote host. (Exception from HRESULT: 0x80072746)" exception is
                // thrown. Maybe only when using ConenctAsync(), not GetOutputStreamAsync().
                uint bytesRead = reader.UnconsumedBufferLength;
                string message = reader.ReadString(bytesRead);

                DisplayOutput(UdpReceiveOutput, "Message received from [" +
                    args.RemoteAddress.DisplayName + "]:" + args.RemotePort + ": " + message);
            }
            catch (Exception ex)
            {
                DisplayOutput(UdpSendOutput, "Peer didn't receive message.");
            }
        }
        /// <summary>
        /// Echo the message back to the peer
        /// </summary>
        /// <param name="peer">The remote peer object</param>
        /// <param name="eventArguments">The received message event arguments</param>
        async void EchoMessage(RemotePeer peer, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            if (!peer.IsMatching(eventArguments.RemoteAddress, eventArguments.RemotePort))
            {
                // In the sample we are communicating with just one peer. To communicate with multiple peers, an
                // application should cache output streams (e.g., by using a hash map), because creating an output
                // stream for each received datagram is costly. Keep in mind though, that every cache requires logic
                // to remove old or unused elements; otherwise, the cache will turn into a memory leaking structure.
                NotifyUserFromAsyncThread(
                    String.Format(
                        "Got datagram from {0}:{1}, but already 'connected' to {2}", 
                        eventArguments.RemoteAddress, 
                        eventArguments.RemotePort, 
                        peer), 
                    NotifyType.ErrorMessage);
            }

            try
            {
                await peer.OutputStream.WriteAsync(eventArguments.GetDataReader().DetachBuffer());
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                NotifyUserFromAsyncThread("Send failed with error: " + exception.Message, NotifyType.ErrorMessage);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Standard event handler which is executed when a multicast message is received.
        /// </summary>
        /// <param name="sender">The socket of the sender of the message</param>
        /// <param name="eventArguments">Arguments which are tied to the event</param>
        // Returns void rather than Task because it's an event handler
        private void MulticastSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            // When we reach this point, we received a broadcast message
            HostName remoteAddress = eventArguments.RemoteAddress;

            uint StrLength = eventArguments.GetDataReader().UnconsumedBufferLength;
            string json = eventArguments.GetDataReader().ReadString(StrLength);

            this.ProcessNetworkObject(json, remoteAddress.CanonicalName);
        }
Exemplo n.º 30
0
		private async void NotifyMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
		{
			var dataReader = args.GetDataReader();
			dataReader.InputStreamOptions = InputStreamOptions.Partial;

			if (dataReader.UnconsumedBufferLength == 0)
			{
				await dataReader.LoadAsync(1024);
			}

			var message = dataReader.ReadString(dataReader.UnconsumedBufferLength);

			try
			{
				var notifyMessage = NotifyMessage.Create(message);

				this.notifyMessages.OnNext(notifyMessage);
			}
			catch (ArgumentException ex)
			{
				logger.Instance().Warning(ex, "The received notification message has been ignored.", "Message".As(message));
			}
		}
        /// <summary>
        /// Message received handler
        /// </summary>
        /// <param name="socket">The socket object</param>
        /// <param name="eventArguments">The datagram event information</param>
        void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            try
            {
                // Interpret the incoming datagram's entire contents as a string.
                uint stringLength = eventArguments.GetDataReader().UnconsumedBufferLength;
                string receivedMessage = eventArguments.GetDataReader().ReadString(stringLength);

                NotifyUserFromAsyncThread(
                    "Received data from remote peer (Remote Address: " +
                    eventArguments.RemoteAddress.CanonicalName +
                    ", Remote Port: " +
                    eventArguments.RemotePort + "): \"" +
                     receivedMessage + "\"",
                    NotifyType.StatusMessage);
            }
            catch (Exception exception)
            {
                SocketErrorStatus socketError = SocketError.GetStatus(exception.HResult);

                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                rootPage.NotifyUser(
                    "Error happened when receiving a datagram:" + exception.Message,
                    NotifyType.ErrorMessage);
            }
        }
 private void _socket_OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs e)
 {
     var reader = e.GetDataReader();
     string message = reader.ReadString(reader.UnconsumedBufferLength);
     Received(this, new PacketEventArgs {Data = message});
 }
Exemplo n.º 33
0
        private async void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            Log($"TICK Received FROM {args.RemoteAddress.DisplayName}");

            using (var reader = args.GetDataReader())
            {
                var length = reader.UnconsumedBufferLength;
                var data = reader.ReadString(length);

                if (data.StartsWith(Protocol.TickTack.ReceiveDeviceInfoCommand))
                {
                    var remoteAddress = args.RemoteAddress;

                    await SendIdentifierToDevice(remoteAddress);                    
                }
            }                       
        }
Exemplo n.º 34
0
        private void OnMessageRecived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            ReadDataFromDevice(args.GetDataReader());

        }