private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            // Dispatch the event to the UI thread so we can update UI.
            var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                string partialOrCompleted = "Partial";

                if (args.IsMessageComplete)
                {
                    partialOrCompleted = "Complete";
                }

                AppendOutputLine(partialOrCompleted + " message received; Type: " + args.MessageType);

                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = UnicodeEncoding.Utf8;

                    try
                    {
                        // Note that it may be possible for partial UTF8 messages to be split between a character if it
                        // extends multiple bytes. We avoid this by using only ASCII characters in this example.
                        // Should your application use multi-byte characters, you will need to do checks for broken characters.
                        string read = reader.ReadString(reader.UnconsumedBufferLength);
                        AppendOutputLine(read);
                    }
                    catch (Exception ex)
                    {
                        AppendOutputLine(MainPage.BuildWebSocketError(ex));
                        AppendOutputLine(ex.Message);
                    }
                }
            });
        }
コード例 #2
0
        async Task SendAsync()
        {
            string message = InputField.Text;

            if (String.IsNullOrEmpty(message))
            {
                rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage);
                return;
            }

            AppendOutputLine("Sending Message: " + message);

            // Buffer any data we want to send.
            messageWriter.WriteString(message);

            try
            {
                // Send the data as one complete message.
                await messageWriter.StoreAsync();
            }
            catch (Exception ex)
            {
                AppendOutputLine(MainPage.BuildWebSocketError(ex));
                AppendOutputLine(ex.Message);
                return;
            }

            rootPage.NotifyUser("Send Complete", NotifyType.StatusMessage);
        }
コード例 #3
0
        private void CloseSocket()
        {
            if (messageWriter != null)
            {
                // In order to reuse the socket with another DataWriter, the socket's output stream needs to be detached.
                // Otherwise, the DataWriter's destructor will automatically close the stream and all subsequent I/O operations
                // invoked on the socket's output stream will fail with ObjectDisposedException.
                //
                // This is only added for completeness, as this sample closes the socket in the very next code block.
                messageWriter.DetachStream();
                messageWriter.Dispose();
                messageWriter = null;
            }

            if (messageWebSocket != null)
            {
                try
                {
                    messageWebSocket.Close(1000, "Closed due to user request.");
                }
                catch (Exception ex)
                {
                    AppendOutputLine(MainPage.BuildWebSocketError(ex));
                    AppendOutputLine(ex.Message);
                }
                messageWebSocket = null;
            }
        }
        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.");
        }
 private void CloseSocket()
 {
     if (messageWebSocket != null)
     {
         try
         {
             messageWebSocket.Close(1000, "Closed due to user request.");
         }
         catch (Exception ex)
         {
             AppendOutputLine(MainPage.BuildWebSocketError(ex));
             AppendOutputLine(ex.Message);
         }
         messageWebSocket = null;
     }
 }
コード例 #6
0
        private async Task ConnectAsync()
        {
            if (String.IsNullOrEmpty(InputField.Text))
            {
                rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage);
                return;
            }

            // 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;
            }

            messageWebSocket = new MessageWebSocket();
            messageWebSocket.Control.MessageType = SocketMessageType.Utf8;
            messageWebSocket.MessageReceived    += MessageReceived;
            messageWebSocket.Closed += OnClosed;

            AppendOutputLine($"Connecting to {server}...");
            try
            {
                await messageWebSocket.ConnectAsync(server);
            }
            catch (Exception ex) // For debugging
            {
                // Error happened during connect operation.
                messageWebSocket.Dispose();
                messageWebSocket = null;

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

            // The default DataWriter encoding is Utf8.
            messageWriter = new DataWriter(messageWebSocket.OutputStream);
            rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
        }
コード例 #7
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);
        }
コード例 #8
0
        private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            // Dispatch the event to the UI thread so we can update UI.
            var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                AppendOutputLine("Message Received; Type: " + args.MessageType);
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = UnicodeEncoding.Utf8;

                    try
                    {
                        string read = reader.ReadString(reader.UnconsumedBufferLength);
                        AppendOutputLine(read);
                    }
                    catch (Exception ex)
                    {
                        AppendOutputLine(MainPage.BuildWebSocketError(ex));
                        AppendOutputLine(ex.Message);
                    }
                }
            });
        }
        async Task SendAsync()
        {
            string message = InputField.Text;

            if (String.IsNullOrEmpty(message))
            {
                rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage);
                return;
            }

            try
            {
                DataWriter messageWriter = new DataWriter();
                messageWriter.WriteString(message);
                IBuffer buffer = messageWriter.DetachBuffer();

                if (EndOfMessageCheckBox.IsChecked == true)
                {
                    AppendOutputLine("Sending end of message: " + message);
                    await messageWebSocket.SendFinalFrameAsync(buffer);
                }
                else
                {
                    AppendOutputLine("Sending partial message: " + message);
                    await messageWebSocket.SendNonfinalFrameAsync(buffer);
                }
            }
            catch (Exception ex)
            {
                AppendOutputLine(MainPage.BuildWebSocketError(ex));
                AppendOutputLine(ex.Message);
                return;
            }

            rootPage.NotifyUser("Send Complete", NotifyType.StatusMessage);
        }
        private async Task ConnectAsync()
        {
            if (String.IsNullOrEmpty(ServerAddressField.Text))
            {
                rootPage.NotifyUser("Please specify a URI to connect to", NotifyType.ErrorMessage);
                return;
            }

            // 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 "Private Networks (Client and Server)" or
            // "Internet (Client)" capability respectively.
            Uri server = rootPage.TryGetUri(ServerAddressField.Text);

            if (server == null)
            {
                return;
            }

            messageWebSocket = new MessageWebSocket();
            messageWebSocket.Control.MessageType = SocketMessageType.Utf8;

            // To support receiving event notifications for partial messages, you must set this receive mode.
            // If you do not set this mode, you will only receive notifications for complete messages; which is
            // the default behavior. Setting to Partial allows us to process partial data as soon as it arrives,
            // as opposed to waiting until the EndOfMessage to process the entire data.
            messageWebSocket.Control.ReceiveMode = MessageWebSocketReceiveMode.PartialMessage;

            messageWebSocket.MessageReceived += MessageReceived;
            messageWebSocket.Closed          += OnClosed;

            if (server.Scheme == "wss")
            {
                // 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
                messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
            }

            AppendOutputLine($"Connecting to {server}...");
            try
            {
                await messageWebSocket.ConnectAsync(server);
            }
            catch (Exception ex) // For debugging
            {
                // Error happened during connect operation.
                messageWebSocket.Dispose();
                messageWebSocket = null;

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

            rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
        }
コード例 #11
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;

            // If we are connecting to wss:// endpoint, by default, the OS performs validation of
            // the server certificate based on well-known trusted CAs. We can perform additional custom
            // validation if needed.
            if (SecureWebSocketCheckBox.IsChecked == true)
            {
                // 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);

                // Add event handler to listen to the ServerCustomValidationRequested event. This enables performing
                // custom validation of the server certificate. The event handler must implement the desired
                // custom certificate validation logic.
                streamWebSocket.ServerCustomValidationRequested += OnServerCustomValidationRequested;

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

            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);
        }
コード例 #12
0
        private async Task ConnectAsync()
        {
            if (String.IsNullOrEmpty(InputField.Text))
            {
                rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage);
                return;
            }

            // 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 null 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 "Private Networks (Client and Server)" or
            // "Internet (Client)" capability respectively.
            Uri server = rootPage.TryGetUri(ServerAddressField.Text);

            if (server == null)
            {
                return;
            }

            messageWebSocket = new MessageWebSocket();
            messageWebSocket.Control.MessageType = SocketMessageType.Utf8;
            messageWebSocket.MessageReceived    += MessageReceived;
            messageWebSocket.Closed += OnClosed;

            // If we are connecting to wss:// endpoint, by default, the OS performs validation of
            // the server certificate based on well-known trusted CAs. We can perform additional custom
            // validation if needed.
            if (SecureWebSocketCheckBox.IsChecked == true)
            {
                // 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
                messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

                // Add event handler to listen to the ServerCustomValidationRequested event. This enables performing
                // custom validation of the server certificate. The event handler must implement the desired
                // custom certificate validation logic.
                messageWebSocket.ServerCustomValidationRequested += OnServerCustomValidationRequested;

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

            AppendOutputLine($"Connecting to {server}...");
            try
            {
                await messageWebSocket.ConnectAsync(server);
            }
            catch (Exception ex) // For debugging
            {
                // Error happened during connect operation.
                messageWebSocket.Dispose();
                messageWebSocket = null;

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

            // The default DataWriter encoding is Utf8.
            messageWriter = new DataWriter(messageWebSocket.OutputStream);
            rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
        }