private async Task ReceiveData(StreamSocket socket)
        {
            ToastNotification notif     = new ToastNotification(ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02));
            XmlNodeList       toastText = notif.Content.GetElementsByTagName("text");

            toastText[0].InnerText = "Device finded, receiving data.";
            ToastNotificationManager.CreateToastNotifier().Show(notif);

            DataReader reader    = new DataReader(socket.InputStream);
            uint       bytesRead = await reader.LoadAsync(sizeof(uint));

            if (bytesRead > 0)
            {
                uint strLength = (uint)reader.ReadInt32();
                bytesRead = await reader.LoadAsync(strLength);

                if (bytesRead > 0)
                {
                    string  receivedData    = reader.ReadString(strLength);
                    Visitor receivedVisitor = JsonConvert.DeserializeObject <Visitor>(receivedData);

                    if (receivedVisitor != null)
                    {
                        //Launch event to start logic.
                        await App.RootFrame.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            var tmp = VisitorReceived;
                            if (tmp != null)
                            {
                                tmp(this, new VisitorEventArgs(receivedVisitor));
                            }
                        });
                    }
                }
            }
            PeerFinder.Stop();
            PeerFinder.Start();
        }
        public void Connect()
        {
            try
            {
                if (Connected)
                {
                    return;
                }
                _clientSocket = new StreamSocket();
                _serverHost   = new HostName(_host);
                //var secLevel = (this.IsSecure) ? SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket;

                var op = _clientSocket.ConnectAsync(_serverHost, _port);

                op.Completed = (info, status) =>
                {
                    switch (status)
                    {
                    case AsyncStatus.Completed:
                        this.SocketConnected.Invoke(this, null);
                        break;

                    case AsyncStatus.Error:
                        this.Disconnect();
                        break;

                    case AsyncStatus.Canceled:
                        this.Disconnect();
                        // Read is not cancelled in this sample.
                        break;
                    }
                };
            }
            catch (Exception)
            {
                this.Disconnect();
            }
        }
Exemple #3
0
        private async Task ProcessRequestAsync(StreamSocket socket)
        {
            Request        request;
            RequestHandler requestHandler = null;
            string         requestText    = null;

            try
            {
                requestText = await RequestUtils.ReadRequest(socket);

                request        = _requestParser.ParseRequestText(requestText, socket.Information.LocalAddress, socket.Information.LocalPort);
                requestHandler = new RequestHandler(socket, request, _staticFileHandler, _requestParser);
                await requestHandler.HandleRequestAsync();
            }
            catch (Exception ex)
            {
                try
                {
                    //await Logger.WriteDebugLog("Error ProcessRequestAsync =>" + ex.Message + "Trace" + ex.StackTrace);
                    await RequestUtils.WriteInternalServerErrorResponse(socket, ex);
                }
                catch (Exception innnerException)
                {
                    //await Logger.WriteDebugLog("Error WriteInternalServerErrorResponse =>" + ex.Message + "Trace" + innnerException.StackTrace);
                }
            }
            finally
            {
                // Clean up by disposing the socket.
                request        = null;
                requestText    = null;
                requestHandler = null;
                if (socket != null)
                {
                    socket.Dispose();
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Internal method to download the content of the download's client connection.
        /// </summary>
        /// <param name="bytesReadDelegate">A <see cref="FileDownloadBytesReadDelegate"/> which is called everytime an array of bytes has been read from the server. /></param>
        /// <param name="downloadFinished">A <see cref="FileDownloadFinished"/> which is called after the entire download has been completed.</param>
        /// <param name="taskCanceled">A <see cref="IOTaskIsCanceledDelegate"/> which is called before each reading cycle to cancel the download.</param>>
        private void beginDownloadData(FileDownloadBytesReadDelegate bytesReadDelegate, FileDownloadFinished downloadFinished, IOTaskIsCanceledDelegate taskCanceled)
        {
            ulong totalReadBytes = 0;
            int   readbytes      = 1;

            byte[] buffer = new byte[10240];

            while (readbytes > 0)
            {
                if (taskCanceled())
                {
                    break;
                }
                try
                {
                    readbytes = _dataChannelSocketReader.Read(buffer, 0, 1024);
                }
                catch (Exception) { break; }
                finally
                {
                    totalReadBytes += (ulong)readbytes;
                    bytesReadDelegate(readbytes, totalReadBytes, buffer);
                }
            }

            _dataChannelSocket.Dispose();
            _dataChannelSocket = null;

            string answer = string.Empty;

            try
            {
                answer = ReadAnswer(ClientType.ActiveClient);
            }
            catch (IOException) { throw; }

            downloadFinished(totalReadBytes);
        }
Exemple #5
0
        private async void OnConnectToServer(object sender, RoutedEventArgs e)
        {
            if (txtIp.Text.Length == 0 || txtPort.Text.Length == 0)
            {
                return;
            }

            Button b = sender as Button;

            b.IsEnabled = false;

            socket = new StreamSocket();
            //StreamSocket socket = new StreamSocket();
            try
            {
                HostName svname = new HostName(txtIp.Text);

                // 连接
                await socket.ConnectAsync(svname, txtPort.Text);

                // 接收数据
                DataReader reader = new DataReader(socket.InputStream);
                reader.UnicodeEncoding = UnicodeEncoding.Utf8; //注意
                // 长度
                await reader.LoadAsync(sizeof(uint));

                uint len = reader.ReadUInt32();
                // 读内容
                await reader.LoadAsync(len);

                string msg = reader.ReadString(reader.UnconsumedBufferLength);

                displayMsg(msg, "System", "left");
            }
            catch (Exception ex)
            {
            }
        }
Exemple #6
0
        private static async Task InitConnectionToHost(string host, string port)
        {
            try
            {
                ClearPrevious();
                socket = new StreamSocket();

                HostName hostNameObj = new HostName(host);
                await socket.ConnectAsync(hostNameObj, port).AsTask();

                Debug.WriteLine("Connected to " + hostNameObj + ":" + port);
                socketIsConnected = true;

                // Start listening feedback from drone
                if (!App.isRPi)
                {
                    PostSocketRead(readBuff);
                }

                if (!App.isRPi)
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        var currentPage     = ((ContentControl)Window.Current.Content).Content as Page;
                        var droneStatus     = currentPage.FindName("droneStatus") as Image;
                        droneStatus.Opacity = 1;
                    });
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("InitConnectionToHost() - " + ex.Message);
                if (!App.isRPi)
                {
                    await new MessageDialog("InitConnectionToHost() - " + ex.Message).ShowAsync();
                }
            }
        }
Exemple #7
0
        private async Task <bool> SetupDeviceConn()
        {
            //Connect to your paired NXTCar using BT + StreamSocket (over RFCOMM)
            PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = "";

            var devices = await PeerFinder.FindAllPeersAsync();

            if (devices.Count == 0)
            {
                MessageBox.Show("No bluetooth devices are paired, please pair your device");
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));

                return(false);
            }

            PeerInformation peerInfo = devices.FirstOrDefault(c => c.DisplayName.Contains("handsense"));

            if (peerInfo == null)
            {
                MessageBox.Show("No paired device was found, please pair your handsense device");
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));

                return(false);
            }

            StreamSocket s = new StreamSocket();

            //This would ask winsock to do an SPP lookup for us; i.e. to resolve the port the
            //device is listening on
            try
            {
                await s.ConnectAsync(peerInfo.HostName, "{00001101-0000-1000-8000-00805F9B34FB}");
            }
            catch { }

            device = new Handsight(s);
            return(device.IsConnected);
        }
        public async void TCPConnect()
        {
            if (m_TCPConnected)
            {
                Debug.WriteLine("Already connected to TCP");
                return;
            }

            try
            {
                Debug.WriteLine("Trying to connect to TCP...");

                serverHost = new HostName(serverHostnameString);
                // Try to connect to the
                await clientTCPSocket.ConnectAsync(serverHost, serverTCPPort);

                m_TCPConnected = true;
                Debug.WriteLine("Connection to TCP established");
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message);
                // 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;
                }

                Debug.WriteLine("Connect to TCP failed with error: " + exception.Message);
                // Could retry the connection, but for this simple example
                // just close the socket.

                // the Close method is mapped to the C# Dispose
                clientTCPSocket.Dispose();
                clientTCPSocket = null;
            }
        }
Exemple #9
0
        public async Task <bool> Connect(string alias, HostName punchServer, string punchServiceName)
        {
            try
            {
                HostName resolvedHost;
                string   serviceName;
                using (var punchSocket = new StreamSocket())
                {
                    await punchSocket.ConnectAsync(punchServer, punchServiceName);

                    using (var punchWriter = new StreamWriter(punchSocket.OutputStream.AsStreamForWrite()))
                        using (var punchReader = new StreamReader(punchSocket.InputStream.AsStreamForRead()))
                        {
                            await punchWriter.WriteLineAsync(JsonConvert.SerializeObject(new PunchRequest {
                                ConnectTo = alias
                            }));

                            await punchWriter.FlushAsync();

                            var response = JsonConvert.DeserializeObject <PunchResponse>(await punchReader.ReadLineAsync());

                            if (!response.Valid)
                            {
                                throw new Exception(response.Message ?? "Could not connect to remote server.");
                            }

                            resolvedHost = new HostName(response.ServerAddress);
                            serviceName  = response.ServerPort;
                        }
                }

                return(await Connect(resolvedHost, serviceName));
            }
            catch
            {
                return(false);
            }
        }
        /// <summary>
        /// Connects the serial port asynchronously
        /// </summary>
        /// <returns></returns>
        public async Task ConnectAsync()
        {
            var services = await Windows.Devices.Enumeration.DeviceInformation
                           .FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

            var names = services.Select(s => s.Name).ToArray();

            //use first serial service
            if (services.Count > 0)
            {
                var id = services[0].Id;

                //use predefined device from constructor
                if (!string.IsNullOrWhiteSpace(device))
                {
                    id = services.Where(x => x.Name.Equals(device, StringComparison.OrdinalIgnoreCase))
                         .Select(x => x.Id).FirstOrDefault();

                    if (id == null)
                    {
                        throw new InvalidOperationException($"Device {device} not found");
                    }
                }

                // Initialize the target Bluetooth device
                var service = await RfcommDeviceService.FromIdAsync(id);

                // Check that the service meets this App's minimum requirement

                _socket = new StreamSocket();
                await _socket.ConnectAsync(service.ConnectionHostName,
                                           service.ConnectionServiceName);

                _writer     = new DataWriter(_socket.OutputStream);
                _readerTask = StartReader();
                IsOpen      = true;
            }
        }
        private async void Disconnect()
        {
            this.playbackService.PlaySoundFromFile(PlaybackService.SoundFiles.Disconnected);
            var notifyEventArgs = new NotifyUIEventArgs()
            {
                NotificationType = NotificationType.ControlMode,
                Name             = "Parked",
                Data             = "Parked"
            };

            this.NotifyUIEvent(notifyEventArgs);

            if (this.writer != null)
            {
                this.writer.DetachStream();
                this.writer = null;
            }

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

            var server = this.httpServer;

            if (server != null)
            {
                await server?.Stop();
            }

            await this.commandProcessor.ExecuteCommandAsync(Commands.DriveStop);

            this.displayManager.ClearRow(1);
            this.displayManager.ClearRow(2);
            this.displayManager.ClearRow(3);
            Debug.Write("Disconected");
        }
Exemple #12
0
        /// <summary>
        /// Start video recording to the passed streamsocket.
        /// Please ensure the streamsocket is connected.
        /// </summary>
        /// <param name="_socket">The video socket to stream to.</param>
        public async void StartVideoRecording(StreamSocket _socket)
        {
            //Make sure the MediaCapture object is initialized
            await CheckSetUp();

            try
            {
                Streamer streamer = new Streamer(_socket);
                // When the streamer is connected, create a new Output stream using the streamer
                currentOutputStream = new OutputVideoStream(streamer);
                // Start recording
                //await _mediaCapture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), currentOutputStream);
                await _mediaCapture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga), currentOutputStream);

                isRecording = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.Source);
                //TODO error management
            }
        }
Exemple #13
0
        public async Task <CharGenResult> CloseAsync()
        {
            if (tcpSocket != null)
            {
                await tcpDw.FlushAsync();

                tcpDw.Dispose();
                tcpSocket.Dispose();
                tcpSocket = null;
                tcpDw     = null;

                // Wait for the TcpReadTask to finish
                if (TcpReadTask != null)
                {
                    await TcpReadTask;
                }
            }
            if (udpSocket != null) //TODO: what other clients need to close their UDP sockets?
            {
                udpSocket = null;
            }
            return(TcpReadEchoResult); // Not really fully correct.
        }
Exemple #14
0
    private void NetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status)
    {
        string cRes = "";

        if (status == AsyncStatus.Completed)
        {
            IsConnected = true;
            // cRes = "Succesfully connected to server.";
            // SendData("CONCT|" + userName);
            ListenerTask = new Task(DoListen);
            ListenerTask.Start();
            Debug.Log("Succesfully connected to server.");
        }
        else
        {
            IsConnected = false;
            socket.Dispose();
            socket = null;
            Debug.Log("Failed to connect to server.");
        }

        isConnecting = false;
    }
Exemple #15
0
    private async void CloseConnection()
    {
        if (socket != null)
        {
            IsReading   = false;
            IsSending   = false;
            IsConnected = false;
            ListenerTask.Wait(100);
            await socket.CancelIOAsync();

            socket.Dispose();
            socket = null;
            Debug.Log("Disconnected from server.");
        }
        else
        {
            IsReading   = false;
            IsSending   = false;
            IsConnected = false;
            socket      = null;
            Debug.Log("No connection to server present.");
        }
    }
Exemple #16
0
        private async void PairAsync()
        {
            try
            {
                var devices =
                    await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

                var device = devices.Single(x => x.Name == "Dev B");
                //var device = devices.Where(x => x.Name == "HC-05");
                _service = await RfcommDeviceService.FromIdAsync(device.Id);

                _socket = new StreamSocket();

                await _socket.ConnectAsync(
                    _service.ConnectionHostName,
                    _service.ConnectionServiceName,
                    SocketProtectionLevel.BluetoothEncryptionWithAuthentication);
            }
            catch (Exception)
            {
                PairAsync();
            }
        }
Exemple #17
0
        //private async Task TryInitializeAppServiceConnection()
        //{
        //    if (_appServiceConnection != null) return;
        //    // Initialize the AppServiceConnection
        //    var appServiceConnection = new AppServiceConnection();
        //    appServiceConnection.PackageFamilyName = "517d6348-bb2f-45b1-89d0-fb7ea8724769_n7wdzm614gaee";
        //    appServiceConnection.AppServiceName = "IotAppService";

        //    // Send a initialize request
        //    var res = await appServiceConnection.OpenAsync();
        //    if (res != AppServiceConnectionStatus.Success)
        //    {
        //        throw new Exception("Failed to connect to the AppService");
        //    }
        //    _appServiceConnection = appServiceConnection;
        //}

        private void WriteResponse(string requestPart, StreamSocket socket)
        {
            try
            {
                if (requestPart.Contains("motorSpeed="))
                {
                    var motorSpeedInt = ExtractIntFromQuerystring(requestPart, "motorSpeed");
                    InvokeOnMotorSpeedChange(motorSpeedInt * .01);
                }
                if (requestPart.Contains("direction="))
                {
                    var directionInt = ExtractIntFromQuerystring(requestPart, "direction");
                    InvokeOnDirectionChange(directionInt * .01);
                }
                WriteResource(socket, "IotWebServer.Default.html");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                // throwing an exceptin here will crash the whole service
                WriteString(socket, ex.ToString());
            }
        }
Exemple #18
0
        public void ClientConnected(StreamSocket socket)
        {
            _tankBot.PlayTone(400);
            _tankBot.SetLED(0, NamedColors.Green);

            lock (_clients)
            {
                var client = Client.Create(socket, _logger);
                client.MessageRecevied += Client_MessageRecevied;
                int attempts = 0;
                while (!_clients.TryAdd(client.Id, client) && attempts++ < 5)
                {
                    SpinWait.SpinUntil(() => false, 5);
                }

                if (attempts == 5)
                {
                    _logger.NotifyUserError("Server_ClientConnected", "Could not add client after 5 attempts.");
                }

                client.StartListening();
            }
        }
        public async Task ReconnectAsync()
        {
            if (MediaStreamSource == null)
            {
                throw new InvalidOperationException();
            }

            metadataPos = 0;

            try
            {
                socketWriter.Dispose();
                socketReader.Dispose();
                socket.Dispose();
            }
            catch (Exception) { }

            connected = false;

            socket = new StreamSocket();

            await ConnectAsync();
        }
Exemple #20
0
        private void OpenConnection()
        {
            streamSocket = new StreamSocket();

            HostName host = new HostName(Server);

            CancellationTokenSource cts = new CancellationTokenSource();

            try
            {
                cts.CancelAfter(timeout * 1000);
                streamSocket.Control.KeepAlive = true;
                var task = streamSocket.ConnectAsync(host, Port.ToString()).AsTask(cts.Token);
                task.Wait();
            }
            catch (TaskCanceledException)
            {
                // we timed out the connection
                streamSocket.Dispose();
                streamSocket = null;
                throw new TimeoutException(Resources.Timeout);
            }
        }
        // Start the send receive operations
        void PeerFinder_StartSendReceive(StreamSocket socket)
        {
            _socket = socket;
            // If the scenario was switched just as the socket connection completed, just close the socket.
            if (!_peerFinderStarted)
            {
                CloseSocket();
                return;
            }

            PeerFinder_SendButton.Visibility = Visibility.Visible;
            PeerFinder_MessageBox.Visibility = Visibility.Visible;

            // Hide the controls related to setting up a connection
            PeerFinder_ConnectButton.Visibility           = Visibility.Collapsed;
            PeerFinder_AcceptButton.Visibility            = Visibility.Collapsed;
            PeerFinder_FoundPeersList.Visibility          = Visibility.Collapsed;
            PeerFinder_BrowsePeersButton.Visibility       = Visibility.Collapsed;
            PeerFinder_StartFindingPeersButton.Visibility = Visibility.Collapsed;
            _dataWriter   = new DataWriter(_socket.OutputStream);
            _socketClosed = false;
            PeerFinder_StartReader(new DataReader(_socket.InputStream));
        }
        /// <summary>
        /// Cleans up the socket and DataWriter and reset the UI
        /// </summary>
        /// <param name="disconnectReason"></param>
        public void Disconnect(string disconnectReason)
        {
            if (chatWriter != null)
            {
                chatWriter.DetachStream();
                chatWriter = null;
            }


            if (chatService != null)
            {
                chatService.Dispose();
                chatService = null;
            }
            lock (this)
            {
                if (chatSocket != null)
                {
                    chatSocket.Dispose();
                    chatSocket = null;
                }
            }
        }
        public async Task <Stream> Initialize(TivoEndPoint endPoint)
        {
            if (this.streamSocket != null)
            {
                throw new InvalidOperationException("Cannot call Initialize on an open interface");
            }

            this.streamSocket = new StreamSocket();

            await this.streamSocket.ConnectAsync(new HostName(endPoint.Address),
                                                 endPoint.Port.ToString(CultureInfo.InvariantCulture),
                                                 SocketProtectionLevel.PlainSocket).AsTask().ConfigureAwait(false);

            var readStream  = this.streamSocket.InputStream.AsStreamForRead();
            var writeStream = this.streamSocket.OutputStream.AsStreamForWrite();

            var tivoTlsClient = new TivoTlsClient(endPoint.Certificate, endPoint.Password);

            this.tlsProtocolHandler = new TlsProtocolHandler(readStream, writeStream);
            this.tlsProtocolHandler.Connect(tivoTlsClient);

            return(this.tlsProtocolHandler.Stream);
        }
        public static async Task<Protocol> CreateProtocolAsync(BluetoothDevice _device)
        {
            try
            {
                StreamSocket socket = new StreamSocket();

                var Services = _device.RfcommServices;
                if (Services.Count > 0)
                {
                    await socket.ConnectAsync(_device.HostName, Services[0].ServiceId.Uuid.ToString("B"));

                    return new Protocol(socket);
                }

                //await socket.ConnectAsync(_device.HostName, Guid.Parse(Pebble_Time_Manager.Common.Constants.PebbleGuid).ToString("B"));

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
            return null;
        }
        /// <summary>
        /// Attempts to connect and send a test message to a TCP host for verification the host exists.
        /// </summary>
        private async Task <bool> TestConnectionAsync(HostName host, string port)
        {
            using (var socket = new StreamSocket())
            {
                try
                {
                    await socket.ConnectAsync(host, port);

                    using (var writer = new StreamWriter(socket.OutputStream.AsStreamForWrite()))
                    {
                        await writer.WriteLineAsync(TEST_MESSAGE);

                        await writer.FlushAsync();
                    }
                }
                catch (Exception)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #26
0
        private async void Disconnection()   //断开连接处理
        {
            if (clientSocket != null)
            {
                clientSocket.Dispose();
                clientSocket = null;
            }

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                //释放资源并清空用户和消息列表

                ClientList.Clear();
                MessageList.Clear();

                DisconnectionButton.IsEnabled = false;
                ConnectionButton.IsEnabled    = true;
                ImgBtn.IsEnabled         = false;
                SendBtn.IsEnabled        = false;
                MessageTextBox.IsEnabled = false;
                MessageTextBox.Text      = "";
            });
        }
Exemple #27
0
        /// <summary>
        /// Boucle de lecture des données reçu. Si l'utilisateur se déconnecte,
        /// une exception est déclanché lors de la lecture et on arrêt la boucle en appelant la méthode ClientDisconnect
        /// </summary>
        private void WaitForData(StreamSocket socket)
        {
            var dr = new StreamReader(socket.InputStream.AsStreamForRead());

            while (_isClientConnected)
            {
                try
                {
                    string message = dr.ReadLine();

                    if (OnMessageReceived != null && !string.IsNullOrEmpty(message))
                    {
                        OnMessageReceived(this, message);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    ClientDisconnect();
                }
            }
            dr.Dispose();
        }
Exemple #28
0
        private async Task Process(StreamSocket socket, String method, String path)
        {
            if (path.ToLower() == "/xml/props.xml")
            {
                await WriteResponseAsync(socket, "application/xml", 200, GetDeviceProps());

                return;
            }

            var rootDirectory = path.ToLower().Split('/');

            if (rootDirectory.Length == 0)
            {
                await WriteResponseAsync(socket, "text/html", 200, String.IsNullOrEmpty(_config.DefaultPageHtml)?DefaultPage : _config.DefaultPageHtml);

                return;
            }

            if (!await HandleRequestAsync(socket, path))
            {
                await WriteResponseAsync(socket, "text/html", 200, String.IsNullOrEmpty(_config.DefaultPageHtml)?DefaultPage : _config.DefaultPageHtml);
            }
        }
Exemple #29
0
        } // End of Constructor

        public async Task <bool> TransmitString(string message)
        {
            try {
                //Create the StreamSocket and establish a connection to the echo server.
                StreamSocket socket = new StreamSocket();

                //Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc.
                //For the echo server/client application we will use a random port 1337.
                await socket.ConnectAsync(_hostName, _portNumber);

                //Write data to the echo server.
                Stream       streamOut = socket.OutputStream.AsStreamForWrite();
                StreamWriter writer    = new StreamWriter(streamOut);
                await writer.WriteLineAsync(message);

                await writer.FlushAsync();

                return(true);
            }
            catch  {
                return(false);
            }
        } // End of TransmitString
Exemple #30
0
        /// <summary>
        /// Connects to the server and requests data.
        /// </summary>
        private bool ConnectListener()
        {
#if !UNITY_EDITOR && UNITY_WSA
            if (waitingForConnection)
            {
                Debug.Log("Not a good time to connect listener");
                return(false);
            }

            waitingForConnection = true;
            Debug.Log("Connecting to " + serverIp);
            HostName networkHost = new HostName(serverIp);
            networkConnection = new StreamSocket();

            IAsyncAction outstandingAction   = networkConnection.ConnectAsync(networkHost, SendConnectionPort.ToString());
            AsyncActionCompletedHandler aach = new AsyncActionCompletedHandler(RcvNetworkConnectedHandler);
            outstandingAction.Completed = aach;

            return(true);
#else
            return(false);
#endif
        }
Exemple #31
0
        async Task<bool> CreateTunnelAsync(HttpWebRequest request, Uri connectUri,
            StreamSocketStream stream /*, out byte[] buffer */)
        {
            bool haveAuth;

            var connectBytes = CreateConnectBytes(request, connectUri, out haveAuth);

            await stream.WriteAsync(connectBytes, 0, connectBytes.Length).ConfigureAwait(false);

            var readHeaders = await ReadHeadersAsync(stream).ConfigureAwait(false);

            var status = readHeaders.Item1;
            var result = readHeaders.Item2;

            if ((!haveAuth || _connectNtlmAuthState == NtlmAuthState.Challenge) &&
                result != null && status == 407)
            {
                // Needs proxy auth
                var connectionHeader = result["Connection"];
                if (_socket != null && !string.IsNullOrEmpty(connectionHeader) &&
                    connectionHeader.ToLower() == "close")
                {
                    // The server is requesting that this connection be closed
                    _socket.Dispose();
                    _socket = null;
                }

                Data.StatusCode = status;
                Data.Challenge = result.GetValues_internal("Proxy-Authenticate", false);
                return false;
            }

            if (status != 200)
            {
                var msg = String.Format("The remote server returned a {0} status code.", status);
                HandleError(WebExceptionStatus.SecureChannelFailure, null, msg);
                return false;
            }

            return result != null;
        }
Exemple #32
0
        async Task ConnectAsync(HttpWebRequest request)
        {
            var isLocked = false;
            try
            {
                Monitor.TryEnter(_socketLock, ref isLocked);

                if (_socket != null && _status == WebExceptionStatus.Success)
                {
                    // Take the chunked stream to the expected state (State.None)
                    if (CanReuse() && await CompleteChunkedReadAsync(CancellationToken.None).ConfigureAwait(false))
                    {
                        _reused = true;
                        return;
                    }
                }

                _reused = false;
                if (_socket != null)
                {
                    _socket.Dispose();
                    _socket = null;
                }

                _chunkStream = null;
            }
            finally
            {
                if (isLocked)
                    Monitor.Exit(_socketLock);
            }

            var hostEntry = await _sPoint.GetHostEntryAsync().ConfigureAwait(false);

            if (hostEntry == null)
            {
#if MONOTOUCH
                    monotouch_start_wwan (sPoint.Address.ToString ());
                    hostEntry = sPoint.HostEntry;
                    if (hostEntry == null) {
#endif
                _status = _sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
                    WebExceptionStatus.NameResolutionFailure;
                return;
#if MONOTOUCH
                    }
#endif
            }

            foreach (var address in hostEntry.AddressList)
            {
                lock (_socketLock)
                {
                    if (null != _socket)
                    {
                        _socket.Dispose();
                        _socket = null;
                    }

                    try
                    {
                        _socket = new StreamSocket();
                    }
                    catch (Exception se)
                    {
                        // The Socket ctor can throw if we run out of FD's
                        if (!request.Aborted)
                            _status = WebExceptionStatus.ConnectFailure;
                        _connectException = se;
                        return;
                    }

                    _socket.Control.NoDelay = !_sPoint.UseNagleAlgorithm;

                    try
                    {
                        _sPoint.KeepAliveSetup(_socket);
                    }
                    catch
                    {
                        // Ignore. Not supported in all platforms.
                    }
                }

                var port = _sPoint.Address.Port;
                var remote = new IPEndPoint(address, port);

                IPEndPoint local;
                if (!_sPoint.GetLocalEndPointFromDelegate(remote, out local))
                {
                    StreamSocket s;
                    lock (_socketLock)
                    {
                        s = _socket;
                        _socket = null;
                        _status = WebExceptionStatus.ConnectFailure;
                    }

                    if (s != null)
                        s.Dispose();

                    return;
                }

                try
                {
                    if (request.Aborted)
                        return;

                    var remoteHostName = new HostName(request.RequestUri.Host);
                    var remoteServiceName = port.ToString(CultureInfo.InvariantCulture);

                    await _socket.ConnectAsync(remoteHostName, remoteServiceName, _ssl ? SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket).AsTask().ConfigureAwait(false);

                    _status = WebExceptionStatus.Success;

                    break;
                }
                catch (ThreadAbortException)
                {
                    // program exiting...
                    StreamSocket s;
                    lock (_socketLock)
                    {
                        s = _socket;
                        _socket = null;
                    }

                    if (s != null)
                        s.Dispose();

                    return;
                }
                catch (ObjectDisposedException)
                {
                    // socket closed from another thread
                    return;
                }
                catch (Exception exc)
                {
                    StreamSocket s;
                    lock (_socketLock)
                    {
                        s = _socket;
                        _socket = null;

                        if (!request.Aborted)
                            _status = WebExceptionStatus.ConnectFailure;
                    }

                    if (s != null)
                        s.Dispose();

                    _connectException = exc;
                }
            }
        }
Exemple #33
0
        //internal IAsyncResult BeginWrite(HttpWebRequest request, byte[] buffer, int offset, int size, AsyncCallback cb, object state)
        //{
        //    Stream s = null;
        //    lock (this)
        //    {
        //        if (Data.Request != request)
        //            throw new ObjectDisposedException(typeof (StreamSocketStream).FullName);
        //        if (_nstream == null)
        //            return null;
        //        s = _nstream;
        //    }

        //    IAsyncResult result = null;
        //    try
        //    {
        //        result = s.BeginWrite(buffer, offset, size, cb, state);
        //        var x = s.WriteAsync(buffer, offset, size).ConfigureAwait(false)
        //    }
        //    catch (Exception)
        //    {
        //        _status = WebExceptionStatus.SendFailure;
        //        throw;
        //    }

        //    return result;
        //}

        //internal bool EndWrite(HttpWebRequest request, bool throwOnError, IAsyncResult result)
        //{
        //    if (request.FinishedReading)
        //        return true;

        //    Stream s = null;
        //    lock (this)
        //    {
        //        if (Data.Request != request)
        //            throw new ObjectDisposedException(typeof(StreamSocketStream).FullName);
        //        if (_nstream == null)
        //            throw new ObjectDisposedException(typeof(StreamSocketStream).FullName);
        //        s = _nstream;
        //    }

        //    try
        //    {
        //        s.EndWrite(result);
        //        return true;
        //    }
        //    catch (Exception exc)
        //    {
        //        _status = WebExceptionStatus.SendFailure;
        //        if (throwOnError && exc.InnerException != null)
        //            throw exc.InnerException;
        //        return false;
        //    }
        //}

        //internal int Read(HttpWebRequest request, byte[] buffer, int offset, int size)
        //{
        //    Stream s = null;
        //    lock (this)
        //    {
        //        if (Data.Request != request)
        //            throw new ObjectDisposedException(typeof(StreamSocketStream).FullName);
        //        if (_nstream == null)
        //            return 0;
        //        s = _nstream;
        //    }

        //    var result = 0;
        //    try
        //    {
        //        var done = false;
        //        if (!_chunkedRead)
        //        {
        //            result = s.Read(buffer, offset, size);
        //            done = (result == 0);
        //        }

        //        if (_chunkedRead)
        //        {
        //            try
        //            {
        //                _chunkStream.WriteAndReadBack(buffer, offset, size, ref result);
        //                if (!done && result == 0 && _chunkStream.WantMore)
        //                    result = EnsureReadAsync(buffer, offset, size);
        //            }
        //            catch (Exception e)
        //            {
        //                HandleError(WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
        //                throw;
        //            }

        //            if ((done || result == 0) && _chunkStream.WantMore)
        //            {
        //                HandleError(WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
        //                throw new WebException("Read error", null, WebExceptionStatus.ReceiveFailure, null);
        //            }
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        HandleError(WebExceptionStatus.ReceiveFailure, e, "Read");
        //    }

        //    return result;
        //}

        internal bool Write(HttpWebRequest request, byte[] buffer, int offset, int size, ref string err_msg)
        {
            err_msg = null;
            Stream s = null;
            lock (this)
            {
                if (Data.Request != request)
                    throw new ObjectDisposedException(typeof(StreamSocketStream).FullName);
                s = _nstream;
                if (s == null)
                    return false;
            }

            try
            {
                s.Write(buffer, offset, size);
                // here SSL handshake should have been done
                if (_ssl && !_certsAvailable)
                    GetCertificates(s);
            }
            catch (Exception e)
            {
                err_msg = e.Message;
                var wes = WebExceptionStatus.SendFailure;
                var msg = "Write: " + err_msg;
                if (e is WebException)
                {
                    HandleError(wes, e, msg);
                    return false;
                }

                // if SSL is in use then check for TrustFailure
                if (_ssl)
                {
#if SECURITY_DEP && MONOTOUCH
                    HttpsClientStream https = (s as HttpsClientStream);
                    if (https.TrustFailure) {
#else
                    if ((bool)_piTrustFailure.GetValue(s, null))
                    {
#endif
                        wes = WebExceptionStatus.TrustFailure;
                        msg = "Trust failure";
                    }
                }

                HandleError(wes, e, msg);
                return false;
            }
            return true;
        }

        internal void Close(bool sendNext)
        {
            lock (this)
            {
                if (Data != null && Data.Request != null && Data.Request.ReuseConnection)
                {
                    Data.Request.ReuseConnection = false;
                    return;
                }

                if (_nstream != null)
                {
                    try
                    {
                        _nstream.Close();
                    }
                    catch
                    { }
                    _nstream = null;
                }

                if (_socket != null)
                {
                    try
                    {
                        _socket.Dispose();
                    }
                    catch
                    { }
                    _socket = null;
                }

                if (_ntlmAuthenticated)
                    ResetNtlm();
                if (Data != null)
                {
                    lock (Data)
                    {
                        Data.ReadState = ReadState.Aborted;
                    }
                }
                _state.SetIdle();
                Data = new WebConnectionData();
                if (sendNext)
                    SendNext();

                _connectRequest = null;
                _connectNtlmAuthState = NtlmAuthState.None;
            }
        }

        void Abort(object sender, EventArgs args)
        {
            lock (this)
            {
                lock (_queue)
                {
                    var req = (HttpWebRequest)sender;
                    if (Data.Request == req || Data.Request == null)
                    {
                        if (!req.FinishedReading)
                        {
                            _status = WebExceptionStatus.RequestCanceled;
                            Close(false);
                            if (_queue.Count > 0)
                            {
                                Data.Request = _queue.Dequeue();
                                SendRequest(Data.Request);
                            }
                        }
                        return;
                    }

                    req.FinishedReading = true;
                    req.SetResponseError(WebExceptionStatus.RequestCanceled, null, "User aborted");
                    if (_queue.Count > 0 && _queue.Peek() == sender)
                        _queue.Dequeue();
                    else if (_queue.Count > 0)
                    {
                        var old = _queue.ToArray();
                        _queue.Clear();
                        for (var i = old.Length - 1; i >= 0; i--)
                        {
                            if (old[i] != sender)
                                _queue.Enqueue(old[i]);
                        }
                    }
                }
            }
        }