示例#1
0
        public async void ConnectInternetTime()
        {
            if (streamWebSocket == null)
            {
                // 记录开始的时间
                startDT = DateTime.UtcNow;

                streamWebSocket = new StreamWebSocket();

                // Don't disable the Nagle algorithm
                streamWebSocket.Control.NoDelay = false;
                streamWebSocket.Closed         += Closed;
                readBuffer = new byte[1000000];
                // Now you can use the StreamWebSocket to call one of the
                // ConnectAsync methods.
                //IWebSocket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket

                try
                {
                    await streamWebSocket.ConnectAsync(new Uri(whost[CurrentHostIndex] + ":" + port));

                    Task receiving = Task.Factory.StartNew(ReceiveData,
                                                           streamWebSocket.InputStream.AsStreamForRead(), TaskCreationOptions.LongRunning);
                }
                catch (Exception xe)
                {
                    SilverlightLFC.common.Environment ex = SilverlightLFC.common.Environment.getEnvironment();
                    ex.WriteFile("log.txt", xe.Message);
                }
                finally
                {
                }
            }
        }
示例#2
0
        public override bool ConnectAsync(TimeSpan timeout, TransportAsyncCallbackArgs callbackArgs)
        {
            StreamWebSocket sws = new StreamWebSocket();

            sws.Control.SupportedProtocols.Add(this.settings.SubProtocol);

            var task = sws.ConnectAsync(this.settings.Uri).AsTask().WithTimeout(timeout, () => "timeout");

            if (task.IsCompleted)
            {
                callbackArgs.Transport = new WebSocketTransport(sws, this.settings.Uri);
                return(false);
            }

            task.ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    callbackArgs.Exception = t.Exception.InnerException;
                }
                else if (t.IsCanceled)
                {
                    callbackArgs.Exception = new OperationCanceledException();
                }
                else
                {
                    callbackArgs.Transport = new WebSocketTransport(sws, this.settings.Uri);
                }

                callbackArgs.CompletedCallback(callbackArgs);
            });
            return(true);
        }
示例#3
0
        public bool SetupTransport(string serviceUri)
        {
            bool result = false;

            lock (this)
            {
                // Save these to help reconnect later.
                serverUri = serviceUri;

                // Set up the ControlChannelTrigger with the stream socket.
                result = RegisterWithControlChannelTrigger(serverUri);
                if (result == false)
                {
                    Diag.DebugPrint("Failed to sign on and connect");
                    if (socket != null)
                    {
                        socket.Dispose();
                        socket     = null;
                        readPacket = null;
                    }
                    if (channel != null)
                    {
                        channel.Dispose();
                        channel = null;
                    }
                }
            }
            return(result);
        }
        private async void OnServerCustomValidationRequested(StreamWebSocket sender, WebSocketServerCustomValidationRequestedEventArgs args)
        {
            // In order to call async APIs in this handler, you must first take a deferral and then
            // release it once you are done with the operation. The "using" statement
            // ensures that the deferral completes when control leaves the block.
            bool isValid;

            using (Deferral deferral = args.GetDeferral())
            {
                // Get the server certificate and certificate chain from the args parameter.
                isValid = await MainPage.AreCertificateAndCertChainValidAsync(args.ServerCertificate, args.ServerIntermediateCertificates);

                if (!isValid)
                {
                    args.Reject();
                }
            }

            // Continue on the UI thread so we can update UI.
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                if (isValid)
                {
                    AppendOutputLine("Custom validation of server certificate passed.");
                }
                else
                {
                    AppendOutputLine("Custom validation of server certificate failed.");
                }
            });
        }
示例#5
0
        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (streamWebSocket != null)
                {
                    rootPage.NotifyUser("Stopping", NotifyType.StatusMessage);
                    streamWebSocket.Close(1000, "Closed due to user request.");
                    streamWebSocket = null;
                }
                else
                {
                    rootPage.NotifyUser("There is no active socket to stop.", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                if (status == WebErrorStatus.Unknown)
                {
                    throw;
                }

                // Normally we'd use the status to test for specific conditions we want to handle specially,
                // and only use ex.Message for display purposes.  In this sample, we'll just output the
                // status for debugging here, but still use ex.Message below.
                rootPage.NotifyUser("Error: " + status, NotifyType.ErrorMessage);

                OutputField.Text += ex.Message + "\r\n";
            }
        }
示例#6
0
        public bool SetupTransport(string socketUri)
        {
            bool result = false;

            lock (this)
            {
                this.socketUri = socketUri;
                result         = RegisterWithControlChannelTrigger(socketUri);

                if (result == false)
                {
                    Diag.DebugPrint("Failed to sign on and connect");

                    if (socket != null)
                    {
                        socket.Close(1001, "Failed to sign on and connect");
                        socket.Dispose();
                        socket = null;
                        reader = null;
                    }

                    if (channel != null)
                    {
                        channel.Dispose();
                        channel = null;
                    }
                }
            }

            return(result);
        }
        private async void StreamToDiskStart_Click(object sender, RoutedEventArgs e)
        {
            var uri = new Uri("ms-appx:///Assets/RecordHS.png", UriKind.Absolute);

            imgRecord.Source = new BitmapImage(uri);
            _askStop         = false;

            try
            {
                var options = new PropertySet();
                options.Add("framerate", "25");
                options.Add("vcodec", "copy");

                var filePicker = new FileSavePicker();
                filePicker.FileTypeChoices.Add("raw H264", new List <string>()
                {
                    ".h264"
                });
                filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;

                StorageFile file = await filePicker.PickSaveFileAsync();

                //var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                var stream = await file.OpenStreamForWriteAsync();

                //long offset = 0;

                _ws = new StreamWebSocket();
                await _ws.ConnectAsync(new Uri(wsuri.Text, UriKind.Absolute));

                DataReader reader = new DataReader(_ws.InputStream);
                do
                {
                    if (_askStop)
                    {
                        return;
                    }

                    var loaded = await reader.LoadAsync(10240);

                    var buf = reader.ReadBuffer(loaded);
                    try
                    {
                        await stream.WriteAsync(buf.ToArray(), 0, (int)buf.Length);

                        //offset += buf.Length;
                    }
                    catch (Exception)
                    {
                        stream.Dispose();
                        return;
                    }
                }while (true);
            }
            catch (Exception err)
            {
                Debug.WriteLine(err.Message);
            }
        }
示例#8
0
 public AppContext(CommModule commInstance, StreamWebSocket webSocket, ControlChannelTrigger channel, string id)
 {
     WebSocketHandle = webSocket;
     Channel         = channel;
     ChannelId       = id;
     CommInstance    = commInstance;
     messageQueue    = new ConcurrentQueue <string>();
 }
示例#9
0
        /// <summary>
        /// WindowsStoreApp Implementation
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        ///
        ///
//        private StreamWebSocket _streamWebSocket;
//
//        private StreamWebSocket _streamWebSocketServer;

        public object CreateWebSocketClientObject()
        {
            StreamWebSocket webSocket = new StreamWebSocket();

            //_streamWebSocket = webSocket;
            //webSocket.Closed += Closed;
            return(webSocket);
        }
        private async Task ConnectWebSocketAsync()
        {
            // Validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not
            // valid WebSocket URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet
            // or intErnet. In these cases the app requires the "Home or Work Networking" or
            // "Internet (Client)" capability respectively.
            Uri server = rootPage.TryGetUri(ServerAddressField.Text);

            if (server == null)
            {
                return;
            }

            // Certificate validation is meaningful only for secure connections.
            if (server.Scheme != "wss")
            {
                AppendOutputLine("Note: Certificate validation is performed only for the wss: scheme.");
            }

            streamWebSocket         = new StreamWebSocket();
            streamWebSocket.Closed += OnClosed;

            // It is okay to set the ClientCertificate property even if GetClientCertificateAsync returns null.
            streamWebSocket.Control.ClientCertificate = await GetClientCertificateAsync();

            // When connecting to wss:// endpoint, the OS by default performs validation of
            // the server certificate based on well-known trusted CAs. For testing purposes, we are ignoring
            // SSL errors.
            // WARNING: Only test applications should ignore SSL errors.
            // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
            // attacks. (Although the connection is secure, the server is not authenticated.)
            // Note that not all certificate validation errors can be ignored.
            // In this case, we are ignoring these errors since the certificate assigned to the localhost
            // URI is self-signed and has subject name = fabrikam.com
            streamWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            streamWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

            AppendOutputLine($"Connecting to {server}...");

            try
            {
                await streamWebSocket.ConnectAsync(server);
            }
            catch (Exception ex) // For debugging
            {
                streamWebSocket.Dispose();
                streamWebSocket = null;

                AppendOutputLine(MainPage.BuildWebSocketError(ex));
                AppendOutputLine(ex.Message);
                return;
            }

            rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
            AppendOutputLine("Connected to WebSocket Server.");
        }
示例#11
0
 private static async Task Receive(StreamWebSocket webSocket)
 {
     byte[] buffer = new byte[receiveChunkSize];
     while (true)
     {                
         await webSocket.InputStream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.None);                
         LogStatus(true, buffer);
     }
 }
示例#12
0
        // This may be triggered remotely by the server or locally by Close/Dispose()
        private void Closed(IWebSocket sender, WebSocketClosedEventArgs args)
        {
            MarshalText(OutputField, "Closed; Code: " + args.Code + ", Reason: " + args.Reason + "\r\n");

            if (streamWebSocket != null)
            {
                streamWebSocket.Dispose();
                streamWebSocket = null;
            }
        }
示例#13
0
        public async Task StartCapture()
        {
            mCancelaationToken?.Cancel();
            if (mStreamWebSocket != null)
            {
                closeSocket(mStreamWebSocket);
            }

            await init();

            mCancelaationToken = new CancellationTokenSource();
            mStartTime         = DateTime.UtcNow;

            try
            {
                await mStreamWebSocket.ConnectAsync(new Uri($"{Globals.WEBSOCKET_ENDPOINT}?device={MainPage.GetUniqueDeviceId()}"));

                var task = Task.Run(async() =>
                {
                    var socket = mStreamWebSocket;
                    while (!mCancelaationToken.IsCancellationRequested)
                    {
                        try
                        {
                            var capturedPhoto = await mLowLagCapture.CaptureAsync();
                            using (var rac = capturedPhoto.Frame.CloneStream())
                            {
                                var dr    = new DataReader(rac.GetInputStreamAt(0));
                                var bytes = new byte[rac.Size];
                                await dr.LoadAsync((uint)rac.Size);
                                dr.ReadBytes(bytes);

                                await socket.OutputStream.WriteAsync(bytes.AsBuffer());
                            }
                        }
                        catch (Exception ex)
                        {
                            AppInsights.Client.TrackException(ex);
                        }

                        if ((DateTime.UtcNow - mStartTime) > mAutoStopAfter)
                        {
                            AppInsights.Client.TrackEvent("CameraAutoTurnOff");
                            mCancelaationToken.Cancel();
                        }
                    }
                }, mCancelaationToken.Token);
            }
            catch (Exception ex)
            {
                mStreamWebSocket.Dispose();
                mStreamWebSocket = null;
                AppInsights.Client.TrackException(ex);
            }
        }
示例#14
0
        // clean up
        private void CloseStream()
        {
            Start.IsEnabled = true;
            End.IsEnabled   = false;

            if (this.streamSocket != null)
            {
                this.streamSocket.Dispose();
                this.streamSocket = null;
            }
        }
示例#15
0
        public void Reset()
        {
            lock (this)
            {
                if (readPacket != null)
                {
                    try
                    {
                        readPacket.DetachStream();
                        readPacket = null;
                    }
                    catch (Exception exp)
                    {
                        Diag.DebugPrint("Could not detach DataReader: " + exp.Message);
                    }
                }

                if (writePacket != null)
                {
                    try
                    {
                        writePacket.DetachStream();
                        writePacket = null;
                    }
                    catch (Exception exp)
                    {
                        Diag.DebugPrint("Could not detach DataWriter: " + exp.Message);
                    }
                }

                if (socket != null)
                {
                    socket.Dispose();
                    socket = null;
                }

                if (channel != null)
                {
                    if (((IDictionary <string, object>)CoreApplication.Properties).ContainsKey(channel.ControlChannelTriggerId))
                    {
                        CoreApplication.Properties.Remove(channel.ControlChannelTriggerId);
                    }

                    // Call the Dispose() method on the controlchanneltrigger object to release any
                    // OS maintained resources for this channel object.
                    channel.Dispose();
                    channel = null;
                }
                Diag.DebugPrint("CommModule has been reset.");
            }
        }
示例#16
0
        private void Closed(IWebSocket sender, WebSocketClosedEventArgs args)
        {
            // You can add code to log or display the code and reason
            // for the closure (stored in args.code and args.reason)

            // This is invoked on another thread so use Interlocked
            // to avoid races with the Start/Stop/Reset methods.
            StreamWebSocket webSocket = Interlocked.Exchange(ref streamWebSocket, null);

            if (webSocket != null)
            {
                webSocket.Dispose();
            }
        }
 private void CloseSocket()
 {
     if (streamWebSocket != null)
     {
         try
         {
             streamWebSocket.Close(1000, "Closed due to user request.");
         }
         catch (Exception ex)
         {
             AppendOutputLine(MainPage.BuildWebSocketError(ex));
             AppendOutputLine(ex.Message);
         }
         streamWebSocket = null;
     }
 }
示例#18
0
        private static async Task Send(StreamWebSocket webSocket)
        {
            var random = new Random();
            byte[] buffer = new byte[sendChunkSize];            

            while (true)
            {
                random.NextBytes(buffer);

                await webSocket.OutputStream.WriteAsync(buffer.AsBuffer());
                LogStatus(false, buffer);
   
                if(delay > TimeSpan.Zero)
                    await Task.Delay(delay);
            }
        }
        private async Task Init()
        {
            try
            {
                mMediaCapture = new MediaCapture();
                await mMediaCapture.InitializeAsync();

                mLowLagCapture = await mMediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateJpeg());

                mStreamWebSocket         = new StreamWebSocket();
                mStreamWebSocket.Closed += MStreamWebSocket_Closed;
            }
            catch (Exception ex)
            {
            }
        }
        // Continuously read incoming data. For reading data we'll show how to use activeSocket.InputStream.AsStream()
        // to get a .NET stream. Alternatively you could call readBuffer.AsBuffer() to use IBuffer with
        // activeSocket.InputStream.ReadAsync.
        private async Task ReceiveDataAsync(StreamWebSocket activeSocket)
        {
            Stream readStream    = streamWebSocket.InputStream.AsStreamForRead();
            int    bytesReceived = 0;

            try
            {
                AppendOutputLine("Background read starting.");

                byte[] readBuffer = new byte[1000];

                while (true)
                {
                    if (streamWebSocket != activeSocket)
                    {
                        // Our socket is no longer active. Stop reading.
                        AppendOutputLine("Background read stopped.");
                        return;
                    }

                    int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length);

                    // Do something with the data.
                    // This sample merely reports that the data was received.

                    bytesReceived         += read;
                    DataReceivedField.Text = bytesReceived.ToString();
                }
            }
            catch (Exception ex)
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                switch (status)
                {
                case WebErrorStatus.OperationCanceled:
                    AppendOutputLine("Background read canceled.");
                    break;

                default:
                    AppendOutputLine("Error: " + status);
                    AppendOutputLine(ex.Message);
                    break;
                }
            }
        }
        // Continuously write outgoing data. For writing data we'll show how to use data.AsBuffer() to get an
        // IBuffer for use with activeSocket.OutputStream.WriteAsync.  Alternatively you can call
        // activeSocket.OutputStream.AsStreamForWrite() to use .NET streams.
        private async Task SendDataAsync(StreamWebSocket activeSocket)
        {
            int bytesSent = 0;

            byte[] data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };

            AppendOutputLine($"Background sending data in {data.Length} byte chunks each second.");

            try
            {
                // Send until the socket gets closed/stopped
                while (true)
                {
                    if (streamWebSocket != activeSocket)
                    {
                        // Our socket is no longer active. Stop sending.
                        AppendOutputLine("Background write stopped.");
                        return;
                    }

                    await activeSocket.OutputStream.WriteAsync(data.AsBuffer());

                    bytesSent         += data.Length;
                    DataSentField.Text = bytesSent.ToString();

                    // Delay so the user can watch what's going on.
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch (Exception ex)
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                switch (status)
                {
                case WebErrorStatus.OperationCanceled:
                    AppendOutputLine("Background write canceled.");
                    break;

                default:
                    AppendOutputLine("Error: " + status);
                    AppendOutputLine(ex.Message);
                    break;
                }
            }
        }
示例#22
0
        public async Task ConnectAsync(Address address)
        {
            StreamWebSocket sws = new StreamWebSocket();

            sws.Control.SupportedProtocols.Add(WebSocketSubProtocol);
            sws.Closed += this.OnWebSocketClosed;

            Uri uri = new UriBuilder()
            {
                Scheme = address.Scheme,
                Port   = GetDefaultPort(address.Scheme, address.Port),
                Host   = address.Host,
                Path   = address.Path
            }.Uri;

            await sws.ConnectAsync(uri);

            this.webSocket = sws;
        }
示例#23
0
        async Task <bool> RegisterWithCCTHelper(string socketUri)
        {
            bool result = false;

            socket = new StreamWebSocket();

            channel = channel.RegisterChannel();

            if (channel == null)
            {
                return(result);
            }

            var socketServer = socketUri.CreateSocketServerUri();

            if (socketServer == null)
            {
                return(result);
            }

            channel.RegisterBackgroundTasks();

            try
            {
                await ConnectSocketChannel(socketUri : socketServer);

                UpdateCoreApplicationProperties();

                PostSocketRead(MAX_BUFFER_LENGTH);

                result = true;

                Diag.DebugPrint("RegisterWithCCTHelper Completed");
            }
            catch (Exception ex)
            {
                Diag.DebugPrint("RegisterWithCCTHelper Task failed with: " + ex.Message);
                return(false);
            }

            return(result);
        }
示例#24
0
        public void Reset()
        {
            lock (this)
            {
                disconnected = true;
                actions      = new InvocationManager();

                if (reader != null)
                {
                    try
                    {
                        reader.DetachStream();
                        reader = null;
                    }
                    catch (Exception ex)
                    {
                        Diag.DebugPrint("Could not detach DataReader: " + ex.Message);
                    }
                }

                if (socket != null)
                {
                    socket.Close(1000, "Socket Reset");
                    socket.Dispose();
                    socket = null;
                }

                if (channel != null)
                {
                    if (CoreApplication.Properties.ContainsKey(channel.ControlChannelTriggerId))
                    {
                        CoreApplication.Properties.Remove(channel.ControlChannelTriggerId);
                    }

                    channel.Dispose();
                    channel = null;
                }

                Diag.DebugPrint("CommModule has been reset.");
            }
        }
示例#25
0
        public async Task StreamToCloudAsync()
        {
            if (this.cloudStreamWebSocket != null)
            {
                this.closeSocket(this.cloudStreamWebSocket);
            }

            this.cloudStreamWebSocket         = new StreamWebSocket();
            this.cloudStreamWebSocket.Closed += this.MStreamWebSocket_Closed;

            try
            {
                await this.cloudStreamWebSocket.ConnectAsync(new Uri(string.Format("{0}{1}", Constants.WebSocketEndpoint, Constants.DeviceId)));

                var task = Task.Run(async() =>
                {
                    var socket = this.cloudStreamWebSocket;
                    while (!this.streamCancellationTokenSource.IsCancellationRequested)
                    {
                        try
                        {
                            if (this._camera.Frame != null)
                            {
                                var clone = this._camera.Frame.ToArray();
                                await socket.OutputStream.WriteAsync(clone.AsBuffer());
                                await Task.Delay(100);
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }, this.streamCancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                this.cloudStreamWebSocket.Dispose();
                this.cloudStreamWebSocket = null;
            }
        }
示例#26
0
        private async Task StartAsync()
        {
            // Validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not
            // valid WebSocket URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet
            // or intErnet. In these cases the app requires the "Home or Work Networking" or
            // "Internet (Client)" capability respectively.
            Uri server = rootPage.TryGetUri(ServerAddressField.Text);

            if (server == null)
            {
                return;
            }

            streamWebSocket         = new StreamWebSocket();
            streamWebSocket.Closed += OnClosed;

            AppendOutputLine($"Connecting to {server}...");
            try
            {
                await streamWebSocket.ConnectAsync(server);
            }
            catch (Exception ex) // For debugging
            {
                streamWebSocket.Dispose();
                streamWebSocket = null;

                AppendOutputLine(MainPage.BuildWebSocketError(ex));
                AppendOutputLine(ex.Message);
                return;
            }
            rootPage.NotifyUser("Connected", NotifyType.StatusMessage);

            // Start a task to continuously read for incoming data
            Task receiving = ReceiveDataAsync(streamWebSocket);

            // Start a task to continuously write outgoing data
            Task sending = SendDataAsync(streamWebSocket);
        }
示例#27
0
        // Start sending primes to the echo service
        private async void Start_OnClick(object sender, RoutedEventArgs e)
        {
            Start.IsEnabled  = false;
            End.IsEnabled    = true;
            this.Primes.Text = string.Empty;

            if (this.streamSocket != null)
            {
                return;
            }

            try
            {
                this.streamSocket = new StreamWebSocket();

                this.streamSocket.Closed +=
                    async(senderSocket, args) =>
                {
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, this.CloseStream);
                };

                await this.streamSocket.ConnectAsync(echoService);

                // we just let these run for the purposes of the demo
                Task.Factory.StartNew(this.ComputePrimes, this.streamSocket.OutputStream, TaskCreationOptions.LongRunning);

                // same here
                Task.Factory.StartNew(
                    this.ReceiveEcho,
                    this.streamSocket.InputStream.AsStreamForRead(),
                    TaskCreationOptions.LongRunning);
            }
            catch (Exception ex)
            {
                this.CloseStream();
                var status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                this.Primes.Text = string.Format("{0}: {1}", ex.Message, status);
            }
        }
示例#28
0
        public static async Task Connect(string uri)
        {
            StreamWebSocket webSocket = null;

            try
            {
                webSocket = new StreamWebSocket();
                await webSocket.ConnectAsync(new Uri(uri));                
                await Task.WhenAll(Receive(webSocket), Send(webSocket));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex);
            }
            finally
            {
                if (webSocket != null)
                    webSocket.Close(1000, string.Empty);
                Console.WriteLine();
                Console.WriteLine("WebSocket closed.");
            }
        }
示例#29
0
        public async Task ConnectWebSocketClientAsync(object webSocketClient, Uri uri, CancellationToken token)
        {
            // Make a local copy to avoid races with the Closed event.
            StreamWebSocket webSocket = webSocketClient as StreamWebSocket;

            //var _streamWebSocket = new StreamWebSocket();
            if (webSocket == null)
            {
                throw new InvalidCastException("cannot cast webSocketClient object to StreamWebSocket");
            }
            try
            {
                await((StreamWebSocket)webSocketClient).ConnectAsync(uri);
                //await _streamWebSocket.ConnectAsync(uri);
                //webSocketClient = _streamWebSocket;
            }
            catch (Exception ex)
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                Debug.WriteLine("Exception during connecting: {0}", ex.Message);
                throw;
            }
        }
        private async void Stream_Click(object sender, RoutedEventArgs e)
        {
            var filePicker = new FileSavePicker();

            filePicker.FileTypeChoices.Add("raw H264", new List <string>()
            {
                ".h264"
            });
            filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;

            StorageFile file = await filePicker.PickSaveFileAsync();

            //var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var fwrite = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.AllowReadersAndWriters);

            var fread = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.AllowReadersAndWriters);

            byte[] startSequence = { 0, 0, 0, 1, 0x27, 0x4d };

            // connect to the Pi
            _ws = new StreamWebSocket();
            await _ws.ConnectAsync(new Uri(wsuri.Text, UriKind.Absolute));

            // detect the start of the samples and write only the chunk of the start
            await H264Helper.Detect(_ws.InputStream, fwrite);

            // start a writing task
            /*await*/ Task.Run(async() => await Helpers.WriteFile(_ws.InputStream, fwrite));

            // buffer some data from the network
            //await Task.Delay(500);

            // start casting
            StartMedia(fread);

            Debug.Write("Started");
        }
示例#31
0
 public async Task StopCapture()
 {
     mCancelaationToken.Cancel();
     mCancelaationToken = null;
     mStreamWebSocket   = null;
 }
示例#32
0
        private async void Start_Click(object sender, RoutedEventArgs e)
        {
            // Have we connected yet?
            if (streamWebSocket != null)
            {
                rootPage.NotifyUser("Already connected", NotifyType.StatusMessage);
                return;
            }

            // By default 'ServerAddressField' is disabled and URI validation is not required. When enabling the
            // text box validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not
            // valid WebSocket URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet
            // or intErnet. In these cases the app requires the "Home or Work Networking" or
            // "Internet (Client)" capability respectively.
            Uri server;

            if (!rootPage.TryGetUri(ServerAddressField.Text, out server))
            {
                return;
            }

            try
            {
                rootPage.NotifyUser("Connecting to: " + server, NotifyType.StatusMessage);

                streamWebSocket = new StreamWebSocket();

                // Dispatch close event on UI thread. This allows us to avoid synchronizing access to streamWebSocket.
                streamWebSocket.Closed += async(senderSocket, args) =>
                {
                    await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Closed(senderSocket, args));
                };

                await streamWebSocket.ConnectAsync(server);

                readBuffer = new byte[1000];

                // Start a background task to continuously read for incoming data
                Task receiving = Task.Factory.StartNew(Scenario2ReceiveData,
                                                       streamWebSocket.InputStream.AsStreamForRead(), TaskCreationOptions.LongRunning);

                // Start a background task to continuously write outgoing data
                Task sending = Task.Factory.StartNew(Scenario2SendData,
                                                     streamWebSocket.OutputStream, TaskCreationOptions.LongRunning);

                rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
            }
            catch (Exception ex) // For debugging
            {
                if (streamWebSocket != null)
                {
                    streamWebSocket.Dispose();
                    streamWebSocket = null;
                }

                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                switch (status)
                {
                case WebErrorStatus.CannotConnect:
                case WebErrorStatus.NotFound:
                case WebErrorStatus.RequestTimeout:
                    rootPage.NotifyUser("Cannot connect to the server. Please make sure " +
                                        "to run the server setup script before running the sample.", NotifyType.ErrorMessage);
                    break;

                case WebErrorStatus.Unknown:
                    throw;

                default:
                    rootPage.NotifyUser("Error: " + status, NotifyType.ErrorMessage);
                    break;
                }

                OutputField.Text += ex.Message + "\r\n";
            }
        }
示例#33
0
 public WebSocketTransport(StreamWebSocket webSocket)
     : this()
 {
     this.webSocket = webSocket;
 }