ReadUInt32() public method

public ReadUInt32 ( ) : uint
return uint
Example #1
2
		private async void StreamSkeleton()
		{
			try
			{
                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
					BinaryReader br = new BinaryReader(ms);

					SkeletonFrameData frame = br.ReadSkeletonFrame();

					SkeletonFrameReadyEventArgs args = new SkeletonFrameReadyEventArgs { SkeletonFrame = frame };
					SkeletonFrame = frame;

					Context.Send(delegate
					{
						if(SkeletonFrameReady != null)
							SkeletonFrameReady(this, args);
					}, null);
				}
			}
			catch(IOException)
			{
                Disconnect();
			}
		}
Example #2
0
        private async void OnRead(Object sender, RoutedEventArgs e)
        {
            StorageFolder local = ApplicationData.Current.LocalFolder;

            StorageFile file = await local.GetFileAsync("demo.dat");
            if(file != null)
            {
                string strres = "读到的内容:\n";
                using(IRandomAccessStream stream = await file.OpenReadAsync())
                {
                    DataReader dr = new DataReader(stream);
                    dr.UnicodeEncoding = UnicodeEncoding.Utf8;
                    await dr.LoadAsync((uint)stream.Size);
                    bool b = dr.ReadBoolean();
                    strres += b.ToString() + "\n";
                    DateTimeOffset dt = dr.ReadDateTime();
                    strres += dt.ToString("yyyy-M-d") + "\n";
                    uint len = dr.ReadUInt32();
                    if(len > 0)
                    {
                        strres += dr.ReadString(len);
                    }
                    dr.Dispose();
                }
                tbResult.Text = strres;
            }
        }
Example #3
0
        private async void Read()
        {
            _reader = new DataReader(_socket.InputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await _reader.LoadAsync(sizeof(uint));
                    //if desconneted
                    if (sizeFieldCount != sizeof(uint))
                        return;

                    uint stringLenght = _reader.ReadUInt32();
                    uint actualStringLength = await _reader.LoadAsync(stringLenght);
                    //if desconneted
                    if (stringLenght != actualStringLength)
                        return;
                    if (OnDataRecived != null)
                        OnDataRecived(_reader.ReadString(actualStringLength));
                }

            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ex.Message);
            }
        }
Example #4
0
        private static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            ConnectionStatus = ConnectionStatus.Connected;
            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await reader.LoadAsync(sizeof (uint));
                    if (sizeFieldCount != sizeof (uint))
                    {
                        return;
                    }
                    
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        return;
                    }

                    Message = reader.ReadString(actualStringLength);
                }
            }
            catch (Exception e)
            {
                ConnectionStatus = ConnectionStatus.Failed;
                //TODO:send a connection status message with error
            }
        }
Example #5
0
		public static async Task<bool> LoadFrom ( ObservableCollection<RecentData> datas )
		{
			try
			{
				StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync ( "data.dat" );
				FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.Read ) as FileRandomAccessStream;
				DataReader dr = new DataReader ( stream );
				dr.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
				dr.ByteOrder = ByteOrder.LittleEndian;

				await dr.LoadAsync ( ( uint ) stream.Size );

				int len = dr.ReadInt32 ();
				for ( int i = 0; i < len; i++ )
				{
					RecentData data = new RecentData ();
					uint srclen = dr.ReadUInt32 ();
					data.Source = dr.ReadString ( srclen );
					data.SourceIndex = dr.ReadInt32 ();
					data.TargetIndex = dr.ReadInt32 ();
					datas.Add ( data );
				}

				stream.Dispose ();
			}
			catch { return false; }
			return true;
		}
Example #6
0
		private async void ColorThread()
		{
			try
			{
                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;
                reader.ByteOrder = ByteOrder.LittleEndian;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
					BinaryReader br = new BinaryReader(ms);

                    ColorFrameReadyEventArgs args = new ColorFrameReadyEventArgs();
                    ColorFrameData cfd = new ColorFrameData();

                    cfd.Format = (ImageFormat)br.ReadInt32();
					cfd.ImageFrame = br.ReadColorImageFrame();

                    MemoryStream msData = new MemoryStream( bytes, (int)ms.Position, (int)(ms.Length - ms.Position) );
                    if (cfd.Format == ImageFormat.Raw)
                    {
                        cfd.RawImage = ms.ToArray();
                    }
                    else
                    {
                        InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                        DataWriter dw = new DataWriter(ras.GetOutputStreamAt(0));
                        dw.WriteBytes(msData.ToArray());
                        await dw.StoreAsync();   

                        // Set to the image
                        BitmapImage bImg = new BitmapImage();
                        bImg.SetSource(ras);
                        cfd.BitmapImage = bImg;
                    }

					ColorFrame = cfd;
					args.ColorFrame = cfd;

                    if (ColorFrameReady != null)
                    {
                        ColorFrameReady(this, args);
                    }
				}
			}
			catch(IOException)
			{
				Disconnect();
			}
		}
Example #7
0
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("Connection Received on Port {0}", sender.Information.LocalPort);
            StreamSocket streamSocket = args.Socket;
            if (streamSocket != null)
            {
                DataReader reader = new DataReader(streamSocket.InputStream);
                try
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the length of the 'packet'.
                    uint length = reader.ReadUInt32();
                    uint actualLength = await reader.LoadAsync(length);
                    if (length != actualLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    string name = reader.ReadString(actualLength);
                    Speaker speaker = new Speaker()
                    {
                        Name = name,
                        Address = streamSocket.Information.RemoteAddress.DisplayName,
                        Status = "Connected",
                        Socket = streamSocket
                    };

                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    () =>
                    {
                        Speakers.Add(speaker);
                    });

                    reader.DetachStream();

                    Debug.WriteLine("New speaker added " + name);

                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in connection received: " + e);
                }
            }
        }
Example #8
0
        private async void DepthThread()
        {
            try {
                short[] depthShort = null;

                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
                    BinaryReader br = new BinaryReader( ms );

                    DepthFrameData dfd = new DepthFrameData();
                    dfd.PlayerIndexBitmask = br.ReadInt32();
                    dfd.PlayerIndexBitmaskWidth = br.ReadInt32();

                    DepthImageFrame frame = br.ReadDepthImageFrame();
                    dfd.ImageFrame = frame;

                    int dataLength = (int)(ms.Length - ms.Position);

                    if ( depthShort == null || depthShort.Length != dataLength / 2 )
                        depthShort = new short[dataLength / 2];

                    Buffer.BlockCopy( bytes, (int)br.BaseStream.Position, depthShort, 0, dataLength );

                    dfd.DepthData = depthShort;

                    DepthFrame = dfd;

                    DepthFrameReadyEventArgs args = new DepthFrameReadyEventArgs();
                    args.DepthFrame = dfd;

                    Context.Send( delegate
                    {
                        if ( DepthFrameReady != null )
                            DepthFrameReady( this, args );
                    }, null );
                }
            }
            catch ( IOException ) {
                Disconnect();
            }
        }
        private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            string id = string.Empty;

            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the string.
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal the text back to the UI thread.
                    string readedString = reader.ReadString(actualStringLength);
                    

                    string action = readedString.Split(';')[0].Split(':')[1].ToString();
                    id = readedString.Split(';')[1].Split(':')[1].ToString();

                    OnReceivedMessage(new ActionEventArgs(action, id));
                }
            }
            catch (Exception exception)
            {
                OnReceivedMessage(new ActionEventArgs("closed", id));
            }
        }
Example #10
0
        public async void StartReader(ConnectedPeer connectedPeer)
        {
            try
            {
                using (var socketReader = new Windows.Storage.Streams.DataReader(connectedPeer._socket.InputStream))
                {
                    // Read the message sent by the remote peer
                    uint bytesRead = await socketReader.LoadAsync(sizeof(uint));

                    if (bytesRead > 0)
                    {
                        uint strLength = (uint)socketReader.ReadUInt32();
                        bytesRead = await socketReader.LoadAsync(strLength);

                        if (bytesRead > 0)
                        {
                            String message = socketReader.ReadString(strLength);
                            OnRaiseMessageEvent(new MessageEventArgs("Got message: " + message));
                            StartReader(connectedPeer); // Start another reader
                        }
                        else
                        {
                            OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                        }
                    }
                    else
                    {
                        OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                    }

                    socketReader.DetachStream();
                }
            }
            catch (Exception e)
            {
                if (!connectedPeer._socketClosed)
                {
                    OnRaiseSocketErrorEvent(new SocketEventArgs("Reading from socket failed: " + e.Message));
                }
            }
        }
Example #11
0
        async void streamSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            int i = 0;
            DataReader dataReader = new DataReader(args.Socket.InputStream);
            DataWriter serverWriter = new DataWriter(args.Socket.OutputStream);
            try
            {
                while (true)
                {
                    uint sizeCount = await dataReader.LoadAsync(4);
                    uint length = dataReader.ReadUInt32();
                    uint contentLength = await dataReader.LoadAsync(length);
                    string msg = dataReader.ReadString(contentLength);
                    i++;
                    Deployment.Current.Dispatcher.BeginInvoke(() => msgList.Children.Add(
                        new TextBlock { Text = "服务器接收到的消息:" + msg }));
                    string serverStr = msg + "|" + i;
                    serverWriter.WriteUInt32(serverWriter.MeasureString(serverStr));
                    serverWriter.WriteString(serverStr);
                    try
                    {
                        await serverWriter.StoreAsync();
                    }
                    catch (Exception err)
                    {
                        if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                        {

                        }
                    }
                }
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {

                }
            }
        }
Example #12
0
        private async void TcpService_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            using (var client = args.Socket)
            using (var dr = new DataReader(client.InputStream))
            using (var dw = new DataWriter(client.OutputStream))
            {
                await dr.LoadAsync(sizeof(Int32));
                var messageLenght = dr.ReadUInt32();

                await dr.LoadAsync(messageLenght);
                var bytes = new Byte[messageLenght];
                dr.ReadBytes(bytes);

                var request = Encoding.UTF8.GetString(bytes);
                var response = "Успешно получено";

                var body = Encoding.UTF8.GetBytes(response);
                dw.WriteUInt32((UInt32)body.Length);
                dw.WriteBytes(body);
                await dw.StoreAsync();
            }
        }
Example #13
0
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            var reader = new DataReader(args.Socket.InputStream);
            _writer = new DataWriter(args.Socket.OutputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    //Caso ocora um desconexão
                    if (sizeFieldCount != sizeof(uint))
                        return;

                    //Tamanho da string
                    uint stringLenght = reader.ReadUInt32();
                    //Ler os dados do InputStream
                    uint actualStringLength = await reader.LoadAsync(stringLenght);
                    //Caso ocora um desconexão
                    if (stringLenght != actualStringLength)
                        return;
                    //Dispara evento de dado recebido
                    if (OnDataRecived != null)
                    {
                        //Le a string com o tamanho passado
                        string data = reader.ReadString(actualStringLength);
                        //Dispara evento de dado recebido
                        OnDataRecived(data);
                    }
                }

            }
            catch (Exception ex)
            {
                // Dispara evento em caso de erro, com a mensagem de erro
                if (OnError != null)
                    OnError(ex.Message);
            }
        }
        private static async Task<string> Receive(StreamSocket socket)
        {
            string result = null;

            if (socket != null)
                using (var reader = new DataReader(socket.InputStream))
                {
                    reader.InputStreamOptions = InputStreamOptions.Partial;

                    uint sizeFieldLength = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldLength == sizeof(uint))
                    {
                        uint dataLength = reader.ReadUInt32();
                        uint actualDataLength = await reader.LoadAsync(dataLength);
                        if (dataLength == actualDataLength)
                            result = reader.ReadString(actualDataLength);
                    }

                    reader.DetachStream();
                }

            return result;
        }
Example #15
0
        /// <summary>
        /// Invoked once a connection is accepted by StreamSocketListener.
        /// </summary>
        /// <param name="sender">The listener that accepted the connection.</param>
        /// <param name="args">Parameters associated with the accepted connection.</param>
        private async void OnConnection(
            StreamSocketListener sender, 
            StreamSocketListenerConnectionReceivedEventArgs args)
        {
            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the string.
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal
                    // the text back to the UI thread.
                    NotifyUserFromAsyncThread(
                        String.Format("Received data: \"{0}\"", reader.ReadString(actualStringLength)), 
                        NotifyType.StatusMessage);
                }
            }
            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(
                    "Read stream failed with error: " + exception.Message, 
                    NotifyType.ErrorMessage);
            }
        }
Example #16
0
        private async void OnConnection(
            StreamSocketListener sender,
            StreamSocketListenerConnectionReceivedEventArgs args)
        {
            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    uint sizeFieldCount1 = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount1 != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the string.
                    uint stringLength = reader.ReadUInt32();
                    uint msgtype = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal
                    // the text back to the UI thread.

                    if (msgtype == 1)
                    {
                        readByte = new byte[actualStringLength];
                        reader.ReadBytes(readByte);
                        receive_byte_flag = 1;
                    }
                    else if (msgtype == 2)
                    {
                        stringtemp = reader.ReadString(actualStringLength);
                        receive_client_ip = 1;
                    }
                    else if (msgtype == 3)
                    {
                        receiverbuf = reader.ReadBuffer(actualStringLength);
                        receive_buf_flag = 1;
                    }
                }
            }
            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;
                }
            }
        }
        /// <summary>
        /// Invoked when the socket listener accepts an incoming Bluetooth connection.
        /// </summary>
        /// <param name="sender">The socket listener that accepted the connection.</param>
        /// <param name="args">The connection accept parameters, which contain the connected socket.</param>
        private async void OnConnectionReceived(
            StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            // Don't need the listener anymore
            socketListener.Dispose();
            socketListener = null;

            try
            {
                socket = args.Socket;
            }
            catch (Exception e)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
                });
                Disconnect();
                return;
            }

            // Note - this is the supported way to get a Bluetooth device from a given socket
            var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName);

            writer = new DataWriter(socket.OutputStream);
            var reader = new DataReader(socket.InputStream);
            bool remoteDisconnection = false;

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                rootPage.NotifyUser("Connected to Client: " + remoteDevice.Name, NotifyType.StatusMessage);
            });            

            // Infinite read buffer loop
            while (true)
            {
                try
                {
                    // Based on the protocol we've defined, the first uint is the size of the message
                    uint readLength = await reader.LoadAsync(sizeof(uint));

                    // Check if the size of the data is expected (otherwise the remote has already terminated the connection)
                    if (readLength < sizeof(uint))
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    uint currentLength = reader.ReadUInt32();

                    // Load the rest of the message since you already know the length of the data expected.  
                    readLength = await reader.LoadAsync(currentLength);

                    // Check if the size of the data is expected (otherwise the remote has already terminated the connection)
                    if (readLength < currentLength)
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    string message = reader.ReadString(currentLength);

                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        ConversationListBox.Items.Add("Received: " + message);
                    });
                }
                // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED).
                catch (Exception ex) when ((uint)ex.HResult == 0x800703E3)
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        rootPage.NotifyUser("Client Disconnected Successfully", NotifyType.StatusMessage);
                    });
                    break;
                }
            }

            reader.DetachStream();
            if (remoteDisconnection)
            {
                Disconnect();
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("Client disconnected",NotifyType.StatusMessage);
                });
            }
        }
Example #18
0
        /// <summary>
        /// Method used for the "Collection Thread"
        /// </summary>
        /// <param name="operation"></param>
        private async void CollectTelemetryData(IAsyncAction operation)
        {
            DataReader reader;
            uint unconsumedBufferLength = 0;
            lock (m_pConnectedSocket)
            {
                reader = new DataReader(m_pConnectedSocket.InputStream);
            }

            while (IsClientConnected | (unconsumedBufferLength > 0))
            {
                await m_pTelemetryReaderSemaphoreSlim.WaitAsync();
                try
                {
                    await reader.LoadAsync(sizeof (byte));
                    unconsumedBufferLength = reader.UnconsumedBufferLength;
                }
                finally
                {
                    m_pTelemetryReaderSemaphoreSlim.Release();
                }
                if (reader.UnconsumedBufferLength <= 0) continue;
                await m_pTelemetryReaderSemaphoreSlim.WaitAsync();
                try
                {
                    byte b;
                    var e = new OnTelemetryDataReceivedEventArgs();
                    b = reader.ReadByte();
                    var commandInformation = (CommandInformation) b;
                    switch (commandInformation)
                    {
                        case CommandInformation.Information:
                            await reader.LoadAsync(sizeof (uint));
                            var n = reader.ReadUInt32();
                            await reader.LoadAsync(n*sizeof (char));
                            e.CommandData = reader.ReadString(n);
                            e.CommandType = CommandInformation.Information;
                            break;
                        case CommandInformation.Gyroscope:
                            float angleX, angleY, angleZ;
                            long gyroTime;
                            await reader.LoadAsync(3*sizeof (double));
                            await reader.LoadAsync(sizeof (long));
                            angleX = Convert.ToSingle(reader.ReadDouble());
                            angleY = Convert.ToSingle(reader.ReadDouble());
                            angleZ = Convert.ToSingle(reader.ReadDouble());
                            gyroTime = reader.ReadInt64();
                            e.CommandData = new GyroscopeData()
                            {
                                Angle = new Vector3(angleX, angleY, angleZ),
                                TimeStamp = new DateTime(gyroTime)
                            };
                            e.CommandType = CommandInformation.Gyroscope;
                            break;
                        case CommandInformation.Accelerometer:
                            float accX, accY, accZ;
                            long accTime;
                            await reader.LoadAsync(3*sizeof (double));
                            await reader.LoadAsync(sizeof (long));
                            accX = Convert.ToSingle(reader.ReadDouble());
                            accY = Convert.ToSingle(reader.ReadDouble());
                            accZ = Convert.ToSingle(reader.ReadDouble());
                            accTime = reader.ReadInt64();
                            e.CommandData = new AccelerometerData()
                            {
                                Acceleration = new Vector3(accX, accY, accZ),
                                TimeStamp = new DateTime(accTime)
                            };
                            e.CommandType = CommandInformation.Accelerometer;
                            break;
                        case CommandInformation.Servo:
                            byte id, velocity;
                            long servoTime;
                            await reader.LoadAsync(2*sizeof (byte));
                            await reader.LoadAsync(sizeof (long));
                            id = reader.ReadByte();
                            velocity = reader.ReadByte();
                            servoTime = reader.ReadInt64();
                            e.CommandData = new ServoControllerData() {ServoId = id, VelocityValue = velocity, TimeStamp = new DateTime(servoTime)};
                            e.CommandType = CommandInformation.Servo;
                            break;
                    }
                    var handler = OnTelemetryDataReceived;
                    handler?.Invoke(this, e);
                }
                finally
                {
                    m_pTelemetryReaderSemaphoreSlim.Release();
                }
            }
        }
        private async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
        {
            try
            {
                await this.textboxDebug.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                    async () =>
                    {
                        this.textboxDebug.Text += "Connection Requested\n";
                        await this.connect(args.PeerInformation);
                        if (_streamsocket != null)
                        {
                            while (true)
                            {
                                // nếu đã tồn tại một thể hiện của lớp DataReader thì đối tượng đó tự động được giải phóng.
                                DataReader datareader = new DataReader(_streamsocket.InputStream);
                                try
                                {
                                    uint size = await datareader.LoadAsync(sizeof(uint));
                                    if (size != sizeof(uint))
                                    {
                                        return;
                                    }
                                    uint lenght = datareader.ReadUInt32();
                                    uint exactlylenght = await datareader.LoadAsync(lenght);
                                    if (lenght != exactlylenght)
                                    {
                                        return;
                                    }
                                    string msg = datareader.ReadString(exactlylenght);
                                    this.textboxDebug.Text += "Receive from " + _streamsocket.Information.RemoteAddress + ": " + msg + "\n";
                                }
                                catch (Exception ex)
                                {
                                    this.textboxDebug.Text += ex.Message + "\n";
                                }
                            }

                        }
                    });
            }
            catch (Exception ex)
            {
                this.textboxDebug.Text += ex.Message + "\n";
            }


            //await PeerFinder.ConnectAsync(args.PeerInformation);
            // throw new NotImplementedException();
        }
Example #20
0
        private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {

            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the string.
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Display the string.
                    string text = reader.ReadString(actualStringLength);

                    // Get the language and the content received
                    char delimiter = ':';
                    string[] res;
                    res = text.Split(delimiter);
                    string InLang = "en";
                    if (res[0].Contains("zh"))
                    {
                        InLang = "zh-CHS";
                    }
                    string outLang = "en";
                    if (selectedLang.LanguageTag.Contains("zh"))
                    {
                        outLang = "zh-CHS";
                    }
                    string content = res[1];

                    Translator Trans = new Translator(content, InLang, outLang);
                    string translatedS = Trans.GetTranslatedString();

                    SpeechSynthesisStream stream = await synthesizer.SynthesizeTextToStreamAsync(translatedS);
                    var ignored = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        media.SetSource(stream, stream.ContentType);
                        media.Play();
                        ReceivedText.Text = text;
                    });
                }
            }
            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;
                }
                var ignored = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    StatusText.Text = "Read stream failed with error: " + exception.Message;
                    StatusText.Text += "Reconnecting Later!";              
                    connected = false;
                    CoreApplication.Properties.Remove("clientSocket");
                    CoreApplication.Properties.Remove("clientDataWriter");
                });
            }
        }
Example #21
0
        private async Task<Command> WaitForCommand(DataReader reader)
        {
            // Wait for a new message, here we wait for enough data to represent the string size
            // if we don't get all of the data, the socket was closed.
            UInt32 sizeFieldCount = await reader.LoadAsync(sizeof(UInt32));
            if (sizeFieldCount != sizeof(uint))
            {
                // We didn't get it all, the socket is closed.
                throw new Exception("Socket closed");
            }

            // Read the string.
            uint stringLength = reader.ReadUInt32();
            uint actualStringLength = await reader.LoadAsync(stringLength);
            if (stringLength != actualStringLength)
            {
                // The underlying socket was closed before we were able to read the whole data.
                throw new Exception("Socket closed");
            }        
            
            // Get the actual string
            string commandString = reader.ReadString(actualStringLength);

            // Parse the command
            return Newtonsoft.Json.JsonConvert.DeserializeObject<Command>(commandString);
        }
        private async Task<String> readMessage(IInputStream input)
        {
            DataReader datareader = new DataReader(input);

            while (true)
            {
                try
                {
                    uint size = await datareader.LoadAsync(sizeof(uint));
                    if (size != sizeof(uint))
                    {
                        return String.Empty;
                    }
                    uint lenght = datareader.ReadUInt32();
                    uint exactlylenght = await datareader.LoadAsync(lenght);
                    if (lenght != exactlylenght)
                    {
                        return String.Empty;
                    }
                    string msg = datareader.ReadString(exactlylenght);
                    return msg;
                }
                catch (Exception ex)
                {
                    this.OutputTextblock.Text += ex.Message + "\n";
                }
            }

        }
        private async void ReceiveStringLoop(DataReader chatReader)
        {
            try
            {
                uint size = await chatReader.LoadAsync(sizeof(uint));
                if (size < sizeof(uint))
                {
                    Disconnect("Remote device terminated connection - make sure only one instance of server is running on remote device");
                    return;
                }

                uint stringLength = chatReader.ReadUInt32();
                uint actualStringLength = await chatReader.LoadAsync(stringLength);
                if (actualStringLength != stringLength)
                {
                    // The underlying socket was closed before we were able to read the whole data
                    return;
                }

                ConversationList.Items.Add("Received: " + chatReader.ReadString(stringLength));

                ReceiveStringLoop(chatReader);
            }
            catch (Exception ex)
            {
                lock (this)
                {
                    if (chatSocket == null)
                    {
                        // Do not print anything here -  the user closed the socket.
                        // HResult = 0x80072745 - catch this (remote device disconnect) ex = {"An established connection was aborted by the software in your host machine. (Exception from HRESULT: 0x80072745)"}
                    }
                    else
                    {
                        Disconnect("Read stream failed with error: " + ex.Message);
                    }
                }
            }
        }
        async void StartReceiveData(DataReader socketReader)
        {
            try
            {
                uint bytesRead = await socketReader.LoadAsync(sizeof(uint));
                if (bytesRead > 0)
                {
                    uint strLength = (uint)socketReader.ReadUInt32();
                    bytesRead = await socketReader.LoadAsync(strLength);
                    if (bytesRead > 0)
                    {
                        byte[] bytesIn = new byte[bytesRead];

                        Debug.WriteLine("ReadBytes");
                        socketReader.ReadBytes(bytesIn);
                        Debug.WriteLine("ReadBytes End");

                       
                        if (DataReceived != null)
                        {
                            DataReceivedEventArgs args = new DataReceivedEventArgs();
                            args.Bytes = bytesIn;
                            DataReceived(this, args);
                        }

                        StartReceiveData(socketReader); // Start another reader
                    }
                    else
                    {
                        SocketError("The remote side closed the socket");
                        socketReader.Dispose();
                        UpdateConnectionStatus(ConnectionStatus.Disconnected);
                    }
                }
                else
                {
                    SocketError("The remote side closed the socket");
                    socketReader.Dispose();
                    UpdateConnectionStatus(ConnectionStatus.Disconnected);
                }
            }
            catch (Exception e)
            {
                if (!_socketClosed)
                {
                    SocketError("Reading from socket failed: " + e.Message);
                }
                socketReader.Dispose();
            }
        }
        public async void StartReader(ConnectedPeer connectedPeer)
        {
            try
            {
                using (var socketReader = new Windows.Storage.Streams.DataReader(connectedPeer._socket.InputStream))
                {
                    // Read the message sent by the remote peer
                    uint bytesRead = await socketReader.LoadAsync(sizeof(uint));
                    if (bytesRead > 0)
                    {
                        uint strLength = (uint)socketReader.ReadUInt32();
                        bytesRead = await socketReader.LoadAsync(strLength);
                        if (bytesRead > 0)
                        {
                            String message = socketReader.ReadString(strLength);
                            OnRaiseMessageEvent(new MessageEventArgs("Got message: " + message));
                            StartReader(connectedPeer); // Start another reader
                        }
                        else
                        {
                            OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                        }
                    }
                    else
                    {
                        OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                    }

                    socketReader.DetachStream();
                }

            }
            catch (Exception e)
            {
                if (!connectedPeer._socketClosed)
                {
                    OnRaiseSocketErrorEvent(new SocketEventArgs("Reading from socket failed: " + e.Message));
                }
            }
        }
Example #26
0
        /// <summary>
        /// When new client is added
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public async void ClientAdded(object sender, EventArgs e)
        {
            var socket = ((CustomEventArgs)e).ClientSocket;

            var clientReader = new DataReader(socket.InputStream);
            clientReader.InputStreamOptions = InputStreamOptions.Partial;

            string clientName;

            while (true)
            {
                uint sizeFieldCount = await clientReader.LoadAsync(sizeof(uint));
                if (sizeFieldCount != sizeof(uint))
                {
                    // The underlying socket was closed before we were able to read the whole data.
                    return;
                }
                uint bytesLength = clientReader.ReadUInt32();
                uint actualBytesLength = await clientReader.LoadAsync(bytesLength);
                if (bytesLength != actualBytesLength)
                {
                    // The underlying socket was closed before we were able to read the whole data.
                    return;
                }
                var buffer = new byte[bytesLength];
                clientReader.ReadBytes(buffer);
                clientName = Encoding.Unicode.GetString(buffer);

                var newClient = new ConnectedClient(clientName, socket);
                clients.Add(newClient);
                break;
            }

            OnClientConnected(socket, clientName);

            foreach (var client in clients)
                SendUsersList(client.Connection, client.UserName, clientName, ChatHelper.CONNECTED);

            var state = new ChatHelper.StateObject
            {
                InputStream = socket.InputStream
            };

            var dataReader = new DataReader(socket.InputStream);


            var buff = new byte[dataReader.UnconsumedBufferLength];
            dataReader.ReadBytes(buff);

            //ChatHelper.WriteToEventLog(Log.ClientConnected, EventLogEntryType.Information);
        }
Example #27
0
 /// <summary>
 /// 监听后连接的事件
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     DataReader reader = new DataReader(args.Socket.InputStream);
     try
     {
         //循环接受数据
         while (true)
         {
             uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
             if (sizeFieldCount != sizeof(uint))
             {
                 //在socket关闭之前才可以读取全部的数据
                 return;
             }
             //读取监听到的信息
             uint stringLength= reader.ReadUInt32();
             uint actualStringLength = await reader.LoadAsync(stringLength);
             if (stringLength != actualStringLength)
             {
                 //在socket关闭之前才可以读取全部的数据
                 return;
             }
             //读取监听到的信息的内容
             string msg = reader.ReadString(actualStringLength);
             //将信息显示到界面
             await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                 {
                     TextBlock tb = new TextBlock { Text = msg, FontSize = 20 };
                     receive_Msg.Children.Add(tb);
                 });
         }
     }
     catch (Exception ex)
     {
         //未知异常
         if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
         {
             throw;
         }
     }
 }
        private async Task<string> Receive()
        {
            if (socket == null) return null;
            

            using (DataReader reader = new DataReader(socket.InputStream))
            {
                

              //  reader.InputStreamOptions = InputStreamOptions.Partial;
                reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                reader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                
                   

                    try
                    {
                    while (true)
                    {
                        StringBuilder ImageStrBuilder = new StringBuilder();
                        // Set the DataReader to only wait for available data (so that we don't have to know the data size)
                        // reader.InputStreamOptions = Windows.Storage.Streams.InputStreamOptions.Partial;
                        // The encoding and byte order need to match the settings of the writer we previously used.


                        // Send the contents of the writer to the backing stream. 
                        // Get the size of the buffer that has not been read.

                        // await  Task.Delay(50);
                        //  if (socket == null) return null;


                        uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                        if (sizeFieldCount != sizeof(uint))
                        {
                            // The underlying socket was closed before we were able to read the whole data.
                            return null;
                        }



                        uint stringLength = reader.ReadUInt32();
                        uint actualStringLength = await reader.LoadAsync(stringLength);
                        if (stringLength != actualStringLength)
                        {
                            // The underlying socket was closed before we were able to read the whole data.
                            return null;
                        }

                        // Keep reading until we consume the complete stream.
                        // while (reader.UnconsumedBufferLength > 0)
                        //     {
                        //        ImageStrBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
                        //        await reader.LoadAsync(2048);

                        //    }



                        //    ImageString = ImageStrBuilder.ToString();


                        //    else if (ImageStrBuilder.Length < 100 && ImageStrBuilder.Length > 0)
                        //    {
                        //         Calculate(ImageString);
                        //     }





                        // ClientAddLine("Received(" + DateTime.Now.ToString("h:mm:ss") + "): " + ImageStrBuilder.ToString());
                        //await Task.Factory.StartNew(ReloadPicture);
                        // Send(2);
                        ImageStrBuilder.Append(reader.ReadString(actualStringLength));

                        // reader.DetachBuffer();
                         reader.DetachStream();
                        // reader.Dispose();

                        return ImageStrBuilder.ToString();
                        //  return "error";


                    }


                    }
                    catch (Exception e)
                    {
                    //   ClientWaitForMessage();
                    //received = false;
                    return "error";
                    }




                
            }


        }
        private async void btnConnect_Tapped(object sender, TappedRoutedEventArgs e)
        {
            // By default 'HostNameForConnect' is disabled and host name validation is not required. When enabling the
            // text box validating the host name is required since it was received from an untrusted source
            // (user input). The host name is validated by catching ArgumentExceptions thrown by the HostName
            // constructor for invalid input.
            HostName hostName;
            try
            {
                hostName = new HostName(this.txtBoxAddress.Text);
            }
            catch (ArgumentException)
            {
                rootPage.ShowMessage("Error: Invalid host name.");
                return;
            }
            this.socketSend = new StreamSocket();

            // If necessary, tweak the socket's control options before carrying out the connect operation.
            // Refer to the StreamSocketControl class' MSDN documentation for the full list of control options.
            this.socketSend.Control.KeepAlive = false;

            try
            {
                rootPage.ShowMessage("Connecting to: " + hostName);

                // Connect to the server (by default, the listener we created in the previous step).
                await this.socketSend.ConnectAsync(hostName, ServiceName);
                isConnect = true;

                rootPage.ShowMessage("Connected");

                await Task.Run(async () =>
                {
                    DataReader reader = new DataReader(this.socketSend.InputStream);

                    try
                    {
                        while (true)
                        {
                            // Read first 4 bytes (length of the subsequent string).
                            uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                            if (sizeFieldCount != sizeof(uint))
                            {
                                // The underlying socket was closed before we were able to read the whole data.
                                return;
                            }

                            // Read the string.
                            uint stringLength = reader.ReadUInt32();
                            uint actualStringLength = await reader.LoadAsync(stringLength);
                            if (stringLength != actualStringLength)
                            {
                                // The underlying socket was closed before we were able to read the whole data.
                                return;
                            }
                            byte[] dataArray = new byte[actualStringLength];
                            reader.ReadBytes(dataArray);


                            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                            {
                                inkCanvas.InkPresenter.StrokeContainer.Clear();

                                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                                await randomAccessStream.WriteAsync(dataArray.AsBuffer());
                                randomAccessStream.Seek(0);
                                await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(randomAccessStream);

                            }).AsTask();

                            // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal
                            // the text back to the UI thread.
                            //Debug.WriteLine(String.Format("Received data: \"{0}\"", reader.ReadString(actualStringLength)));
                            //string str = reader.ReadString(actualStringLength);
                        }
                    }
                    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)
                        {
                            rootPage.ShowMessage("Connect failed with error: " + exception.Message);
                        }
                    }

                });
            }
            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)
                {
                    rootPage.ShowMessage("Connect failed with error: " + exception.Message);
                }
            }
        }
Example #30
0
        /// <summary>
        /// Invoked when the socket listener accepted an incoming Bluetooth connection.
        /// </summary>
        /// <param name="sender">The socket listener that accecpted the connection.</param>
        /// <param name="args">The connection accept parameters, which contain the connected socket.</param>
        private async void OnConnectionReceived(
            StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                NotifyStatus("Client Connected");

                // Don't need the listener anymore
                socketListener.Dispose();
                socketListener = null;

                socket = args.Socket;

                writer = new DataWriter(socket.OutputStream);

                var reader = new DataReader(socket.InputStream);
                bool remoteDisconnection = false;
                while (true)
                {
                    uint readLength = await reader.LoadAsync(sizeof(uint));
                    if (readLength < sizeof(uint))
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    uint currentLength = reader.ReadUInt32();

                    readLength = await reader.LoadAsync(currentLength);
                    if (readLength < currentLength)
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    string message = reader.ReadString(currentLength);

                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        ConversationListBox.Items.Add("Received: " + message);
                    });
                }

                reader.DetachStream();
                if (remoteDisconnection)
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Disconnect();
                        NotifyStatus("Client disconnected.");
                    });
                }
            }
            catch (Exception e)
            {
                NotifyError(e);
            }
        }
        private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            DataReader reader = new DataReader(args.Socket.InputStream);
            socketReceive = args.Socket;
            this.isConnect = true;
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                this.txtBoxAddress.Text = "Connected";
            });

            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the string.
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }
                    byte[] dataArray = new byte[actualStringLength];
                    reader.ReadBytes(dataArray);

                    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                    {
                        //set new ink
                        inkCanvas.InkPresenter.StrokeContainer.Clear();

                        InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                        await randomAccessStream.WriteAsync(dataArray.AsBuffer());
                        randomAccessStream.Seek(0);
                        await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(randomAccessStream);

                    }).AsTask();
                }
            }
            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)
                {
                    rootPage.ShowMessage(
                  "Start Receive failed with error: " + exception.Message);
                }
            }
        }