コード例 #1
0
ファイル: Utils.cs プロジェクト: cephalin/ContosoMoments
        public static async Task<bool> CheckServerAddressWP(string url, int port = 80, int msTimeout = 5000)
        {
            bool retVal = false;
            string originalUrl = url;

            if (!IsUrlValid(url))
                return retVal;

            try
            {
                using (var tcpClient = new StreamSocket())
                {
                    url = url.Replace("http://", string.Empty).Replace("https://", string.Empty);
                    if (url.Last() == '/')
                        url = url.Substring(0, url.Length - 1);

                    await tcpClient.ConnectAsync(new Windows.Networking.HostName(url), port.ToString(), SocketProtectionLevel.PlainSocket);

                    if (tcpClient.Information.RemoteHostName.ToString().ToLower() == url.ToLower())
                        retVal = true;

                    tcpClient.Dispose();
                }
            }
            catch (Exception ex)
            {
                retVal = false;
            }

            retVal &= await ExposesContosoMomentsWebAPIs(originalUrl);

            return retVal;
        }
コード例 #2
0
 public async void ConnectTo(Slide slide)
 {
     var duration = slide.AppearanceDuration;
     var content = slide.Content as ScreenCapture;
     var ipAddress = content.IPTargetAgent;
     HostName localHost = null;
     foreach (var hostName in NetworkInformation.GetHostNames())
     {
         if(hostName.IPInformation != null)
         {
             if(hostName.Type == Windows.Networking.HostNameType.Ipv4)
             {
                 localHost = hostName;
             }
         }
     }
     var TCPClient = new StreamSocket();
     try
     {
         var cts = new CancellationTokenSource();
         cts.CancelAfter(500);
         var connectAsync = TCPClient.ConnectAsync(
             new Windows.Networking.EndpointPair(localHost, "54321", new Windows.Networking.HostName(ipAddress), "54321"));
         var connectTask = connectAsync.AsTask(cts.Token);
         await connectTask;
         this.SendToAgent(slide, TCPClient);
     }
     catch(Exception ex)
     {
         TCPClient.Dispose();
         Debug.WriteLine(ex.Message);
         this.FireOnConnectionFailed();
         return;
     }
 }
コード例 #3
0
        public async void ConnectAsync(string ipOrHost, int port, SocketEventArgs args)
        {
            _socket = new StreamSocket();
            var server = new HostName(ipOrHost);

            // TCP timeouts in WinRT are excessive, shorten them here using task cancellation
            var cts = new CancellationTokenSource();

            try
            {
                cts.CancelAfter(MqttProtocolInformation.Settings.NetworkTimeout * 1000);
                _logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Authenticating client certificate with remote host CN={0}", server.CanonicalName));
                await _socket.ConnectAsync(server, port.ToString(), GetSocketProtectionLevel(args.EncryptionLevel)).AsTask(cts.Token);
                _clientUid = args.ClientUid;
                StartReceiving();
            }
            catch (TaskCanceledException)
            {
                args.SocketException = new IOException("Timeout error while trying to connect.");
                _clientUid = null;
                _socket.Dispose();
                _socket = null;
            }
            catch (Exception ex)
            {
                args.SocketException = ex;
                _clientUid = null;
                _socket.Dispose();
                _socket = null;
            }
            args.Complete();
        }
コード例 #4
0
        private async void ReceiveImage(StreamSocket socket)
        {
            // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
            var reader = new DataReader(socket.InputStream);

            // Anzahl der Bytes abrufen, aus denen das Bild besteht
            // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
            await reader.LoadAsync(4);
            int imageSize = reader.ReadInt32();

            // Bytearray des Bildes laden
            await reader.LoadAsync((uint)imageSize);
            byte[] imageBytes = new byte[imageSize];
            reader.ReadBytes(imageBytes);
            
            // Bytearray in Stream laden und anzeigen
            using (var ms = new MemoryStream(imageBytes))
            {
                var image = new BitmapImage();
                image.SetSource(ms);

                ReceivedImage.Source = image;
            }
            Status.Text = "Bild empfangen.";

            // Ressourcen freigeben
            reader.Dispose();
            socket.Dispose();
        }
コード例 #5
0
ファイル: TCP_connector.cs プロジェクト: Herrandy/HRC-TUNI
    public void CloseSocket()
    {
        exchangeStopRequested = true;
#if UNITY_EDITOR
        if (exchangeThread != null)
        {
            exchangeThread.Abort();
            stream.Close();
            client.Close();
            writer.Close();
            reader.Close();
            stream         = null;
            exchangeThread = null;
        }
#endif
#if !UNITY_EDITOR
        Debug.Log("OnCloseSocket");
        if (exchangeTask != null)
        {
            exchangeTask.Wait();
            writer.Dispose();
            reader.Dispose();
            socket.Dispose();
            socket       = null;
            exchangeTask = null;
        }
#endif
        connected = false;
        writer    = null;
        reader    = null;
    }
コード例 #6
0
        public static void Connect(string address, string port)
        {
            if (!connected)
            {
                clientSocket = new StreamSocket();

                try
                {
                    serverHost = new HostName(address);
                    serverPort = port;
                    serverHostnameString = address;
                    writer = new DataWriter(clientSocket.OutputStream);

                    clientSocket.ConnectAsync(serverHost, serverPort);
                    connected = true;
                }
                catch (Exception)
                {
                    clientSocket.Dispose();
                    clientSocket = null;

                    throw new ConnectionErrorException();
                }
            }
            else
            {
                clientSocket.Dispose();
                clientSocket = null;
                connected = false;

                GamepadClient.Connect(address, port);
            }
        }
コード例 #7
0
ファイル: HttpServer.cs プロジェクト: wleev/Catnap.Server
        private async void ProcessRequestAsync(StreamSocket socket)
        {
            HttpRequest request;
            try
            {
                request = HttpRequest.Read(socket);
            }
            catch (Exception ex)
            {
                await WriteInternalServerErrorResponse(socket, ex);
                return;
            }

            if (AcceptedVerbs.Contains(request.Method.Method))
            {
                HttpResponse response;
                try
                {
                    response = await restHandler.Handle(request);
                }
                catch (Exception ex)
                {
                    await WriteInternalServerErrorResponse(socket, ex);
                    return;
                }
                await WriteResponse(response, socket);

                await socket.CancelIOAsync();
                socket.Dispose();
            }
        }
コード例 #8
0
    public void StopExchange()
    {
        exchangeStopRequested = true;

#if UNITY_EDITOR
        if (exchangeThread != null)
        {
            exchangeThread.Abort();
            stream.Close();
            client.Close();
            writer.Close();
            reader.Close();

            stream         = null;
            exchangeThread = null;
        }
#else
        if (exchangeTask != null)
        {
            exchangeTask.Wait();
            socket.Dispose();
            writer.Dispose();
            reader.Dispose();

            socket       = null;
            exchangeTask = null;
        }
#endif
        writer = null;
        reader = null;
    }
コード例 #9
0
    public async void SendMessage(string message)
    {
        Windows.Networking.Sockets.StreamSocket streamSocket = null;
        streamSocket = new Windows.Networking.Sockets.StreamSocket();
        try
        {
            Debug.Log("Trying to connect");
            await streamSocket.ConnectAsync(HostAddress, "1337");

            Debug.Log("Connected!");
            Stream       streamOut = streamSocket.OutputStream.AsStreamForWrite();
            StreamWriter writer    = new StreamWriter(streamOut);
            await writer.WriteLineAsync(message);

            Debug.Log("The following message was sent: " + message);
            await writer.FlushAsync();

            //creat input stream and read it into a string (for responses from RPI3)

            /*Stream streamIn = streamSocket.InputStream.AsStreamForRead();
             * StreamReader reader = new StreamReader(streamIn);
             * string response = await reader.ReadLineAsync();*/
        }
        catch (Exception e)
        {
            //catch an error messages and display
            Debug.Log(e.Message);
        }
        finally
        {
            //end by disposing the socket and clearing the resources
            streamSocket.Dispose();
        }
    }
コード例 #10
0
    public void StopExchange()
    {
        exchangeStopRequested = true;
#if UNITY_EDITOR
        if (client != null)
        {
            client.Close();
            client = null;
        }
#else
        if (displayImageCoroutine != null)
        {
            StopCoroutine(displayImageCoroutine);
        }
        if (readImageCoroutine != null)
        {
            StopCoroutine(readImageCoroutine);
        }
        if (coroutine != null)
        {
            StopCoroutine(coroutine);
        }
        if (socket != null)
        {
            socket.Dispose();
            socket = null;
        }
#endif
    }
コード例 #11
0
    public void StopExchange()
    {
        writer.Write("!\n");

        //if (exchangeTask != null) {
        //    exchangeTask.Wait();

        socket.Dispose();
        writer.Dispose();
        reader.Dispose();

        socket       = null;
        exchangeTask = null;
        //}

        writer = null;
        reader = null;
    }
コード例 #12
0
ファイル: SmtpStream.cs プロジェクト: dronamiusSlIVA/MailKit
 void DropConnection()
 {
     if (Socket != null)
     {
         try {
             Socket.Dispose();
         } catch {
             return;
         }
     }
 }
コード例 #13
0
ファイル: Server.cs プロジェクト: sm6uax/plegma
        //------------------------------------------------------------------------------------------------------------------------
        public void Stop(bool CloseAllChannels = false)
        {
            try
            {
                lock (this)
                {
                    //close all channels
                    if (CloseAllChannels)
                    {
                        _Channels.ForEach(c => { try { c.Close("Server stopped"); } catch (Exception ex) { DebugEx.Assert(ex, "Error while closing channel"); } });
                        _Channels.Clear();
                    }

                    //update flag
                    if (!_IsRunning)
                    {
                        return;
                    }
                    else
                    {
                        _IsRunning = false;
                    }

                    //close my socket
                    try
                    {
                        if (sock != null)
                        {
#if NETFX
                            try { sock.Close(); } catch { }
#endif
                            try { sock.Dispose(); } catch { }
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugEx.TraceErrorException(ex);
                    }
                    sock = null;

                    //wait for task finish
#if NETFX
                    PortListener?.Join(1000);
#elif UNIVERSAL
                    PortListener?.Wait(1000);
#endif
                    PortListener = null;
                }
            }
            catch (Exception ex)
            {
                DebugEx.Assert(ex, "YPChannel Server Stop() failed");
            }
        }
コード例 #14
0
ファイル: SmtpStream.cs プロジェクト: GitObjects/MailKit
        void DropConnection()
        {
            if (Socket != null)
            {
#if NETSTANDARD_2_0 || NET_4_5 || __MOBILE__
                Socket.Disconnect(false);
#else
                Socket.Dispose();
#endif
            }
        }
コード例 #15
0
ファイル: SynchronousSocket.cs プロジェクト: djaus2/SurfPad
 public static void CloseSocket()
 {
     try
     {
         streamSocket.Dispose();
     }
     catch (Exception ex)
     {
         Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
         MainPage.MP.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
     }
 }
コード例 #16
0
    /// <summary>
    ///     Read messages from server.
    ///     Blocking
    /// </summary>
    /// <returns>
    ///     String of the msg
    ///     If there is no data then return null!!
    /// </returns>
    public String Read()
    {
        String received = "";

        try
        {
            received = reader.ReadLine();
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
#if !UNITY_EDITOR
            socket.Dispose();
#else
            client.Close();
#endif
            throw e;
        }
        Debug.Log("TcpClientHandler Read : " + received);
        return(received);
    }
コード例 #17
0
ファイル: Device.cs プロジェクト: syabiku/BTDevices
		public async Task StartAsync()
		{
			if (tcs != null)
				return;
			if (m_device == null)
				throw new ObjectDisposedException("Device");
			tcs = new System.Threading.CancellationTokenSource();
			socket = new StreamSocket();
			await socket.ConnectAsync(
#if NETFX_CORE
								m_device.ConnectionHostName,
								m_device.ConnectionServiceName);
#else
								m_device.HostName, "1");
			//socket = await Windows.Networking.Proximity.PeerFinder.ConnectAsync(m_device.HostName;
#endif
			if (tcs.IsCancellationRequested) //Stop was called while opening device
			{
				socket.Dispose();
				socket = null;
				throw new TaskCanceledException();
			} var token = tcs.Token;
			var _ = Task.Run(async () =>
			{
				var stream = socket.InputStream.AsStreamForRead();
				byte[] buffer = new byte[1024];
				while (!token.IsCancellationRequested)
				{
					int readCount = 0;
					try
					{
						readCount = await stream.ReadAsync(buffer, 0, 1024, token).ConfigureAwait(false);
					}
					catch { }
					if (token.IsCancellationRequested)
						break;
					if (readCount > 0)
					{
						OnData(buffer.Take(readCount).ToArray());
					}
					await Task.Delay(10, token);
				}
				if(socket != null)
					socket.Dispose();
				if (closeTask != null)
					closeTask.SetResult(true);
			});
		}
コード例 #18
0
        public async Task ConnectAsync(Uri url, CancellationToken cancellationToken)
        {
            var host = url.Host;
            var serviceName = url.Port.ToString(CultureInfo.InvariantCulture);
            var hostName = new HostName(host);

            var useTls = string.Equals("HTTPS", url.Scheme, StringComparison.OrdinalIgnoreCase);

            if (!useTls && !string.Equals("HTTP", url.Scheme, StringComparison.OrdinalIgnoreCase))
                throw new NotSupportedException("Scheme not supported: " + url.Scheme);

            var socket = new StreamSocket();

            if (null != Interlocked.CompareExchange(ref _socket, socket, null))
            {
                socket.Dispose();
                throw new InvalidOperationException("The socket is in use");
            }

            try
            {
                socket.Control.NoDelay = true;

#if WINDOWS_PHONE8
                var protectionLevel = useTls ? SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket;
#else
                var protectionLevel = useTls ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
#endif

                await socket.ConnectAsync(hostName, serviceName, protectionLevel)
                    .AsTask(cancellationToken)
                    .ConfigureAwait(false);
            }
            catch (Exception)
            {
                Close();

                throw;
            }

            //if (useTls)
            //{
            //    var cert = socket.Information.ServerCertificate;
            //    var certFingerprint = cert.GetHashValue("SHA256");
            //}
        }
コード例 #19
0
    public void StopExchange()
    {
        exchangeStopRequested = true;

        if (exchangeTask != null)
        {
            exchangeTask.Wait();
            socket.Dispose();
            writer.Dispose();
            reader.Dispose();

            socket       = null;
            exchangeTask = null;
        }

        writer = null;
        reader = null;
    }
コード例 #20
0
        private async void HandleRequest(StreamSocket socket) {
            //Initialize IO classes
            var reader = new DataReader(socket.InputStream) { InputStreamOptions = InputStreamOptions.Partial };
            var writer = new DataWriter(socket.OutputStream) {
                UnicodeEncoding = UnicodeEncoding.Utf8
            };

            var acceptedRequest = new AcceptedRequest();
            await acceptedRequest.AcceptRequest(reader);

            String response = ProcessRequest(acceptedRequest.request, acceptedRequest.content);

            //create response
            writer.WriteString(Responder.CreateResponse(response));
            await writer.StoreAsync();

            socket.Dispose();
        }
コード例 #21
0
        public async Task ConnectAsync()
        {
            if (ConnectionInProgress) return;

            ConnectionAttemptInformation = "";
            ConnectionInProgress = true;

            try
            {
                using (var tcpClient = new StreamSocket())
                {
                    await tcpClient.ConnectAsync(
                        new Windows.Networking.HostName(HostName),
                        PortNumber,
                        SocketProtectionLevel.PlainSocket);

                    var localIp = tcpClient.Information.LocalAddress.DisplayName;
                    var remoteIp = tcpClient.Information.RemoteAddress.DisplayName;

                    ConnectionAttemptInformation = String.Format("Success, remote server contacted at IP address {0}",
                                                                 remoteIp);
                    tcpClient.Dispose();
                }
            }
            catch (Exception ex)
            {
                if (ex.HResult == -2147013895)
                {
                    ConnectionAttemptInformation = "Error: No such host is known";
                }
                else if (ex.HResult == -2147014836)
                {
                    ConnectionAttemptInformation = "Error: Timeout when connecting (check hostname and port)";
                }
                else
                {
                    ConnectionAttemptInformation = "Error: Exception returned from network stack: " + ex.Message;
                }
            }
            finally
            {
                ConnectionInProgress = false;
            }
        }
コード例 #22
0
ファイル: SocketTerminal.xaml.cs プロジェクト: djaus2/SurfPad
        public void CloseSocket()
        {
            try
            {
                outputStream = null;
                streamWriter = null;
                inputStream  = null;
                streamReader = null;

                streamSocket.Dispose();
                _Mode       = Mode.Disconnected;
                Status.Text = "Socekt Disconnected";
            }
            catch (Exception ex)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
                MainPage.MP.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
            }
        }
コード例 #23
0
        private async void send_file_tcp(String ipadd, int port)
        {            
            try
            {  
                _tcpclient = new StreamSocket();

                await _tcpclient.ConnectAsync(new HostName(ipadd), port.ToString());
                _datawriter = new DataWriter(_tcpclient.OutputStream);

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.GetFileAsync(this.filepath);

                IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync();
                
                _datareader = new DataReader(filestream);

                while ((_length = await _datareader.LoadAsync(63 * 1024)) != 0)
                {
                    _tosend = new byte[_length];

                    _datareader.ReadBytes(_tosend);

                    _datawriter.WriteBytes(_tosend);
                    await _datawriter.StoreAsync();
                }

                filestream.Dispose();
                _datareader.Dispose();
                _datawriter.Dispose();

                _tcpclient.Dispose();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _stopwatch.Stop();
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, ipadd);
            }            
        }
コード例 #24
0
ファイル: PlStreamCustom.cs プロジェクト: Vahen/HoloProj
    /// <summary>
    /// Permet de déconnecter le client du serveur
    /// </summary>
    private void OnApplicationQuit()
    {
        try {
            // signal shutdown
            stopListening = true;
#if UNITY_EDITOR
            if (conThread == null || stream == null)
            {
                Debug.Log("PlStreamCustom not started, nothing to close");
                return;
            }
            // attempt to join for 500ms
            if (!conThread.Join(500))
            {
                // force shutdown
                conThread.Abort();
                if (tcpClient != null)
                {
                    tcpClient.Close();
                    tcpClient = null;
                }
                stream.Close();
            }
#else
            if (exchangeTask != null)
            {
                exchangeTask.Wait();
                socket.Dispose();
                stream.Close();
                socket       = null;
                exchangeTask = null;
            }
            else
            {
                Debug.Log("PlStreamCustom not started, nothing to close");
            }
#endif
        }
        catch (Exception e) {
            Debug.Log(e);
            Debug.Log("[polhemus] PlStream was unable to close the connection thread upon application exit. This is not a critical exception.");
        }
    }
コード例 #25
0
ファイル: ReceiveAndWriteFile.cs プロジェクト: Vahen/HoloProj
    /// <summary>
    /// Permet de déconnecter le client du serveur
    /// </summary>
    private void OnApplicationQuit()
    {
        try {
            // signal shutdown
            stopListening = true;
#if !UNITY_EDITOR
            if (exchangeTask != null)
            {
                exchangeTask.Wait();
                socket.Dispose();
                stream.Close();
                socket       = null;
                exchangeTask = null;
            }
#endif
        }
        catch (Exception e) {
            Debug.Log(e);
        }
    }
コード例 #26
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="SmtpStream"/> and
        /// optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources;
        /// <c>false</c> to release only the unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && !disposed)
            {
                IsConnected = false;
                Stream.Dispose();
                disposed = true;

#if NETFX_CORE
                if (Socket != null)
                {
                    Socket.Dispose();
                    Socket = null;
                }
#else
                Socket = null;
#endif
            }

            base.Dispose(disposing);
        }
コード例 #27
0
ファイル: Logger.cs プロジェクト: 88to/titanium_mobile
		static async void multicastSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs eventArguments) {
			try {
				HostName remoteHostAddress = eventArguments.RemoteAddress;
				uint len = eventArguments.GetDataReader().UnconsumedBufferLength;
				string message = eventArguments.GetDataReader().ReadString(len).Trim();
				int p = message.IndexOf(':');
				if (p != -1) {
					string serverLogToken = message.Substring(0, p);
					int port = Int32.Parse(message.Substring(p + 1));

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

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

							// shutdown the multicast socket and start the tcp connection
							multicastSocket.Dispose();
						} catch {
							if (tcpWriter != null) {
								tcpWriter.Dispose();
								tcpWriter = null;
							}
							if (tcpSocket != null) {
								tcpSocket.Dispose();
								tcpSocket = null;
							}
						}
					}
				}
			} catch (Exception ex) {
				if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) {
					throw;
				}
				Debug.WriteLine(ex.ToString());
			}
		}
コード例 #28
0
ファイル: SendMail.cs プロジェクト: IcePlus/KidsPainter
 public async void sendMail(string strSendTo,string strContent , Boolean hasPicture)
 {
     HostName hostName = new HostName(hostIP);
     StreamSocket socket = new StreamSocket();
     List<string[]> storeList = new List<string[]>();
     try
     {
         await socket.ConnectAsync(hostName, port);
     }
     catch (Exception exception)
     {
         if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
         {
             throw;
         }
     }
     StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp");
     StorageFile pic = await folder.GetFileAsync("MyPainter.png");
     IBuffer buffer = await FileIO.ReadBufferAsync(pic);
     DataWriter writer = new DataWriter(socket.OutputStream);
     writer.WriteUInt32(writer.MeasureString(strSendTo));
     writer.WriteString(strSendTo);
     writer.WriteUInt32(writer.MeasureString(strContent));
     writer.WriteString(strContent);
     if (hasPicture)
     {
         writer.WriteUInt32((uint)buffer.Length);
         writer.WriteBuffer(buffer);
     }
     else
     {
         writer.WriteUInt32(0);
         writer.WriteString("");
     }
     await writer.StoreAsync();
     writer.DetachStream();
     writer.Dispose();
     socket.Dispose();
 }
コード例 #29
0
        private async void TransferPicture(StreamSocket socket)
        {
            // DataWriter erzeugen, um Byte-Umwandlung erledigen zu lassen...
            var writer = new DataWriter(socket.OutputStream);

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.PhotoBytesToShare.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.PhotoBytesToShare);
            await writer.StoreAsync();
            await writer.FlushAsync();
            UpdateStatus("Übertragung abgeschlossen.");

            // Ressourcen freigeben
            writer.Dispose();
            socket.Dispose();

            // Beenden der Annahme von Client-Verbindungen
            _listener.Dispose();
        }
コード例 #30
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);
      }
    }
コード例 #31
0
        private async void SocketListener_ConnectionReceived()
        {
            try
            {
                //Create the StreamSocket and establish a connection to the echo server.
                Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();

                //The server hostname that we will be establishing a connection to. We will be running the server and client locally,
                //so we will use localhost as the hostname.
                Windows.Networking.HostName serverHost = new Windows.Networking.HostName("raspberrypi");

                //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.
                string serverPort = "51717";
                await socket.ConnectAsync(serverHost, serverPort);

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

                await writer.FlushAsync();

                //Read data from the echo server.
                Stream       streamIn = socket.InputStream.AsStreamForRead();
                StreamReader reader   = new StreamReader(streamIn);
                string       response = await reader.ReadLineAsync();

                textBox1.Text = response;
                socket.Dispose();
            }
            catch (Exception e)
            {
                //Handle exception here.
            }
        }
コード例 #32
0
        async private void ConnectDevice_Click(object sender, RoutedEventArgs e)
        {
            //Revision: No need to requery for Device Information as we alraedy have it:
            DeviceInformation DeviceInfo; // = await DeviceInformation.CreateFromIdAsync(this.TxtBlock_SelectedID.Text);
            PairedDeviceInfo pairedDevice = (PairedDeviceInfo)ConnectDevices.SelectedItem;
            DeviceInfo = pairedDevice.DeviceInfo;

            bool success = true;
            try
            {
                _service = await RfcommDeviceService.FromIdAsync(DeviceInfo.Id);

                if (_socket != null)
                {
                    // Disposing the socket with close it and release all resources associated with the socket
                    _socket.Dispose();
                }

                _socket = new StreamSocket();
                try
                {
                    // Note: If either parameter is null or empty, the call will throw an exception
                    await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);
                }
                catch (Exception ex)
                {
                    success = false;
                    System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message);
                }
                // If the connection was successful, the RemoteAddress field will be populated
                if (success)
                {
                    this.buttonDisconnect.IsEnabled = true;
                    this.buttonSend.IsEnabled = true;
                    this.buttonStartRecv.IsEnabled = true;
                    this.buttonStopRecv.IsEnabled = false;
                    string msg = String.Format("Connected to {0}!", _socket.Information.RemoteAddress.DisplayName);
                    //MessageDialog md = new MessageDialog(msg, Title);
                    System.Diagnostics.Debug.WriteLine(msg);
                    //await md.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message);
                _socket.Dispose();
                _socket = null;
            }
        }
コード例 #33
0
ファイル: XHRProxy.cs プロジェクト: El-Ruaan/titanium_mobile
		private async void handleRequest(StreamSocket socket) {
			Logger.log("XHRProxy", "Received incoming HTTP request");

			DataWriter writer = new DataWriter(socket.OutputStream);
			writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

			// deny any request that isn't from localhost
			if (socket.Information.RemoteAddress.RawName != "::1") {
				Logger.log("XHRProxy", "403 Forbidden; remote address \"" + socket.Information.RemoteAddress.RawName + "\" != \"::1\"");
				requestError(writer, socket, "403 Forbidden", "Forbidden");
				return;
			}

			DataReader reader = new DataReader(socket.InputStream);
			reader.InputStreamOptions = InputStreamOptions.Partial;

			RequestParseState state = RequestParseState.GetRequest;
			string urlPrefix = "/fetch/" + this.securityToken + "/";
			UInt32 numBytesRead = 0;
			UInt32 requestBufferSize = 4096;
			string buffer = "";
			string httpMethod = "";
			string url = "";
			bool isLocalFile = true;
			Uri httpUri = null;
			int p, q;
			bool needMoreData = true;
			HttpWebRequest request = null;
			Dictionary<string, string> headers = new Dictionary<string,string>();
			int responseBufferSize = 4096;
			int responseBytesRead = 0;
			int responseTotalBytesRead = 0;
			byte[] responseBuffer = new byte[responseBufferSize];

			try {
				while (true) {
					Logger.log("XHRProxy", "State = " + states[(int)state]);

					if (needMoreData) {
						numBytesRead = await reader.LoadAsync(requestBufferSize);
						Logger.log("XHRProxy", "Read " + numBytesRead + " bytes");
						buffer += reader.ReadString(numBytesRead);
					}

					switch (state) {
						case RequestParseState.GetRequest:
							// go until first \n
							p = buffer.IndexOf("\r\n");
							if (p != -1) {
								// parse out the request
								string[] tokens = buffer.Substring(0, p).Split(' ');
								if (tokens.Length != 3) {
									Logger.log("XHRProxy", "400 Bad Request; request had " + tokens.Length + " tokens, expected 3");
									requestError(writer, socket, "400 Bad Request", "Bad Request");
									return;
								}

								httpMethod = tokens[0].ToUpper();
								Logger.log("XHRProxy", "Method = " + httpMethod);

								url = tokens[1];
								q = url.IndexOf(urlPrefix);
								if (q != 0) {
									Logger.log("XHRProxy", "400 Bad Request");
									requestError(writer, socket, "400 Bad Request", "Bad Request");
									return;
								}

								string encodedUrl = url.Substring(q + urlPrefix.Length);
								string decodedUrl = HttpUtility.UrlDecode(encodedUrl).Replace(' ', '+');
								byte[] data = Convert.FromBase64String(decodedUrl);
								url = Encoding.UTF8.GetString(data, 0, data.Length);
								if (url.IndexOf("http://") == 0 || url.IndexOf("https://") == 0) {
									isLocalFile = false;
								}
								Logger.log("XHRProxy", "URL = " + url);

								buffer = buffer.Substring(p + 2);
								needMoreData = false;
								state = RequestParseState.Headers;
							} else if (numBytesRead < requestBufferSize) {
								// not enough data, bad request
								Logger.log("XHRProxy", "400 Bad Request; not enough data");
								requestError(writer, socket, "400 Bad Request", "Bad Request");
								return;
							} else {
								// need more data
								Logger.log("XHRProxy", "Need more data...");
								needMoreData = true;
							}
							break;

						case RequestParseState.Headers:
							p = buffer.IndexOf("\r\n\r\n"); // two line breaks
							if (p != -1) {
								Logger.log("XHRProxy", "Original HTTP Request Headers:");
								string[] lines = buffer.Substring(0, p).Split('\n');
								foreach (string line in lines) {
									q = line.IndexOf(':');
									if (q != -1) {
										string name = line.Substring(0, q);
										string value = line.Substring(q + 2).Trim();
										Logger.log("XHRProxy", "    " + name + ": " + value);
										headers[name] = value;
									} else {
										Logger.log("XHRProxy", "    Bad HTTP header \"" + line + "\", ignoring");
									}
								}

								buffer = buffer.Substring(p + 4);
								state = isLocalFile ? RequestParseState.ServeFile : RequestParseState.CreateRequest;
							} else if (numBytesRead < requestBufferSize) {
								// not enough data, bad request
								Logger.log("XHRProxy", "400 Bad Request; not enough data");
								requestError(writer, socket, "400 Bad Request", "Bad Request");
								return;
							} else {
								// need more data
								Logger.log("XHRProxy", "Need more data...");
								needMoreData = true;
							}

							if (state == RequestParseState.ServeFile) {
								continue;
							}
							break;

						case RequestParseState.ServeFile:
							string originalFile = url;
							string file = collapsePath(originalFile);
							if (file.IndexOf("..") == 0) {
								Logger.log("XHRProxy", "400 Bad Request");
								Logger.log("XHRProxy", "Original file: " + originalFile);
								Logger.log("XHRProxy", "Resolved file: " + file);
								requestError(writer, socket, "400 Bad Request", "The requested file must not begin with \"..\"");
								return;
							}

							file = file.Replace('/', '\\');

							if (file.StartsWith("\\")) {
								file = "App" + file;
							} else {
								file = "App\\" + file;
							}

							StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
							StorageFile theFile;
							try {
								theFile = await installFolder.GetFileAsync(file);
							} catch (Exception e) {
								Logger.log("XHRProxy", "404 File Not Found");
								Logger.log("XHRProxy", "Original file: " + originalFile);
								Logger.log("XHRProxy", "Resolved file: " + file);
								requestError(writer, socket, "404 File Not Found", "File Not Found");
								return;
							}

							var randomAccessStream = await theFile.OpenReadAsync();
							Stream fs = randomAccessStream.AsStreamForRead();

							FileInfo fi = new FileInfo(file);
							string ext = fi.Extension.Substring(1); // trim the dot

							string mimetype = "application/octet-stream";
							if (mimeTypes.ContainsKey(ext)) {
								mimetype = mimeTypes[ext];
							}

							Logger.log("XHRProxy", "Status: 200 OK");
							Logger.log("XHRProxy", "Actual HTTP headers being returned:");
							Logger.log("XHRProxy", "    Content-Type: " + mimetype);
							Logger.log("XHRProxy", "    Content-Length: " + fi.Length);
							Logger.log("XHRProxy", "    Connection: close");

							writer.WriteString("HTTP/1.0 200 OK\r\n");
							writer.WriteString("Content-Type: " + mimetype + "\r\n");
							writer.WriteString("Content-Length: " + fi.Length + "\r\n");
							writer.WriteString("Connection: close\r\n\r\n");

							while ((responseBytesRead = fs.Read(responseBuffer, 0, responseBuffer.Length)) > 0) {
								responseTotalBytesRead += responseBytesRead;
								writer.WriteBytes(responseBuffer);
							}
							Logger.log("XHRProxy", "Returned " + responseTotalBytesRead + " bytes");

							await writer.StoreAsync();
							socket.Dispose();
							return;

						case RequestParseState.CreateRequest:
							httpUri = new Uri(url, UriKind.Absolute);
							request = (HttpWebRequest)WebRequest.CreateHttp(httpUri);
							request.Method = httpMethod;

							Logger.log("XHRProxy", "Actual HTTP headers being sent:");
							foreach (string key in headers.Keys) {
								if (key == "Accept") {
									Logger.log("XHRProxy", "    Accept: " + headers[key]);
									request.Accept = headers[key];
								} else if (key == "Content-Type") {
									if (httpMethod == "POST" || httpMethod == "PUT") {
										Logger.log("XHRProxy", "    Content-Type: " + headers[key]);
										request.ContentType = headers[key];
									}
								} else if (key == "Host") {
									Logger.log("XHRProxy", "    Host: " + httpUri.Host);
									request.Headers["Host"] = httpUri.Host;
								} else {
									Logger.log("XHRProxy", "    " + key + ": " + headers[key]);
									request.Headers[key] = headers[key];
								}
							}

							if (httpMethod == "POST" || httpMethod == "PUT") {
								Stream requestStream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null);
								byte[] jsonAsBytes = Encoding.UTF8.GetBytes(buffer);
								Logger.log("XHRProxy", "Body:");
								Logger.log("XHRProxy", buffer);
								await requestStream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);

								if (numBytesRead == requestBufferSize) {
									// pump the rest of the data
									while (true) {
										numBytesRead = await reader.LoadAsync(requestBufferSize);
										if (numBytesRead == 0) {
											break;
										}
										Logger.log("XHRProxy", "Read " + numBytesRead + " bytes");
										buffer = reader.ReadString(numBytesRead);
										Logger.log("XHRProxy", buffer);
										byte[] jsonAsBytes2 = Encoding.UTF8.GetBytes(buffer);
										await requestStream.WriteAsync(jsonAsBytes2, 0, jsonAsBytes2.Length);
										if (numBytesRead < requestBufferSize) {
											break;
										}
									}
								}

								requestStream.Close();
							}

							Logger.log("XHRProxy", "Sending request...");
							request.BeginGetResponse(async callbackResult => {
								try {
									Logger.log("XHRProxy", "Reading response...");
									HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);

									Logger.log("XHRProxy", "Status: " + (int)response.StatusCode + " " + response.StatusDescription);
									writer.WriteString("HTTP/1.0 " + (int)response.StatusCode + " " + response.StatusDescription + "\r\n");

									Logger.log("XHRProxy", "Original HTTP response headers:");
									foreach (string key in response.Headers.AllKeys) {
										Logger.log("XHRProxy", "    " + key + ": " + response.Headers[key]);
									}

									Logger.log("XHRProxy", "Actual HTTP headers being returned:");
									foreach (string key in response.Headers.AllKeys) {
										if (key == "Connection") {
											Logger.log("XHRProxy", "    Connection: close");
											writer.WriteString("Connection: close\r\n");
										} else {
											Logger.log("XHRProxy", "    " + key + ": " + response.Headers[key]);
											writer.WriteString(key + ": " + response.Headers[key] + "\r\n");
										}
									}
									writer.WriteString("\r\n");

									Stream responseStream = response.GetResponseStream();
									BinaryReader br = new BinaryReader(responseStream);
									byte[] responseBytes = br.ReadBytes(4096);
									while (responseBytes.Length > 0) {
										responseTotalBytesRead += responseBytes.Length;
										writer.WriteBytes(responseBytes);
										responseBytes = br.ReadBytes(4096);
									}
									Logger.log("XHRProxy", "Returned " + responseTotalBytesRead + " bytes");

									await writer.StoreAsync();
									socket.Dispose();
								} catch (WebException ex) {
									// check if we have an expired or self-signed cert
									if (ex.Status == WebExceptionStatus.UnknownError) {
										if (ex.Response.Headers.Count == 0 && httpUri.Scheme == "https") {
											Logger.log("XHRProxy", "Invalid SSL certificate, returning a 400 Bad Request");
											requestError(writer, socket, "400 Bad Request", "Invalid SSL certificate");
										} else {
											Logger.log("XHRProxy", "File not found, returning a 404");
											requestError(writer, socket, "404 File Not Found", "File Not Found");
										}
									} else {
										Logger.log("XHRProxy", "400 Bad Request");
										Logger.log("XHRProxy", ex.Status.ToString());
										requestError(writer, socket, "400 Bad Request", ex.Status.ToString());
									}
									return;
								}
							}, null);

							return;
					}
				}
			} catch (Exception ex) {
				Logger.log("XHRProxy", "500 Internal Server Error");
				foreach (string s in ex.ToString().Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)) {
					Logger.log("XHRProxy", s);
				}
				requestError(writer, socket, "500 Internal Server Error", ex.Message);
			}
		}
コード例 #34
0
        private static async Task Send(StreamSocket socket, object data)
        {
            if (socket != null)
            {
                using (var writer = new DataWriter(socket.OutputStream))
                {
                    var str = Transport.Serialize(data);
                    writer.WriteUInt32(writer.MeasureString(str));
                    writer.WriteString(str);

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

                    writer.DetachStream();
                }

                await socket.CancelIOAsync();
                socket.Dispose();
            }
        }
コード例 #35
0
ファイル: SmtpClient.cs プロジェクト: erdonet/MailKit
		/// <summary>
		/// Establishes a connection to the specified SMTP or SMTP/S server.
		/// </summary>
		/// <remarks>
		/// <para>Establishes a connection to the specified SMTP or SMTP/S server.</para>
		/// <para>If the <paramref name="port"/> has a value of <c>0</c>, then the
		/// <paramref name="options"/> parameter is used to determine the default port to
		/// connect to. The default port used with <see cref="SecureSocketOptions.SslOnConnect"/>
		/// is <c>465</c>. All other values will use a default port of <c>25</c>.</para>
		/// <para>If the <paramref name="options"/> has a value of
		/// <see cref="SecureSocketOptions.Auto"/>, then the <paramref name="port"/> is used
		/// to determine the default security options. If the <paramref name="port"/> has a value
		/// of <c>465</c>, then the default options used will be
		/// <see cref="SecureSocketOptions.SslOnConnect"/>. All other values will use
		/// <see cref="SecureSocketOptions.StartTlsWhenAvailable"/>.</para>
		/// <para>Once a connection is established, properties such as
		/// <see cref="AuthenticationMechanisms"/> and <see cref="Capabilities"/> will be
		/// populated.</para>
		/// <para>Note: The connection established by any of the
		/// <a href="Overload_MailKit_Net_Smtp_SmtpClient_Connect.htm">Connect</a>
		/// methods may be re-used if an application wishes to send multiple messages
		/// to the same SMTP server. Since connecting and authenticating can be expensive
		/// operations, re-using a connection can significantly improve performance when
		/// sending a large number of messages to the same SMTP server over a short
		/// period of time.</para>
		/// </remarks>
		/// <example>
		/// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessage"/>
		/// </example>
		/// <param name="host">The host name to connect to.</param>
		/// <param name="port">The port to connect to. If the specified port is <c>0</c>, then the default port will be used.</param>
		/// <param name="options">The secure socket options to when connecting.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="host"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="port"/> is not between <c>0</c> and <c>65535</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// The <paramref name="host"/> is a zero-length string.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="SmtpClient"/> has been disposed.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// The <see cref="SmtpClient"/> is already connected.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// <paramref name="options"/> was set to
		/// <see cref="MailKit.Security.SecureSocketOptions.StartTls"/>
		/// and the SMTP server does not support the STARTTLS extension.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="SmtpCommandException">
		/// An SMTP command failed.
		/// </exception>
		/// <exception cref="SmtpProtocolException">
		/// An SMTP protocol error occurred.
		/// </exception>
		public override void Connect (string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (host == null)
				throw new ArgumentNullException ("host");

			if (host.Length == 0)
				throw new ArgumentException ("The host name cannot be empty.", "host");

			if (port < 0 || port > 65535)
				throw new ArgumentOutOfRangeException ("port");
			
			CheckDisposed ();

			if (IsConnected)
				throw new InvalidOperationException ("The SmtpClient is already connected.");

			capabilities = SmtpCapabilities.None;
			AuthenticationMechanisms.Clear ();
			MaxSize = 0;

			SmtpResponse response;
			Stream stream;
			bool starttls;
			Uri uri;

			ComputeDefaultValues (host, ref port, ref options, out uri, out starttls);

#if !NETFX_CORE
			var ipAddresses = Dns.GetHostAddresses (host);
			Socket socket = null;

			for (int i = 0; i < ipAddresses.Length; i++) {
				socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

				try {
					cancellationToken.ThrowIfCancellationRequested ();

					if (LocalEndPoint != null)
						socket.Bind (LocalEndPoint);

					socket.Connect (ipAddresses[i], port);
					break;
				} catch (OperationCanceledException) {
					socket.Dispose ();
					socket = null;
					throw;
				} catch {
					socket.Dispose ();
					socket = null;

					if (i + 1 == ipAddresses.Length)
						throw;
				}
			}

			if (socket == null)
				throw new IOException (string.Format ("Failed to resolve host: {0}", host));

			this.host = host;

			if (options == SecureSocketOptions.SslOnConnect) {
				var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
				ssl.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
				stream = ssl;
			} else {
				stream = new NetworkStream (socket, true);
			}
#else
			var protection = options == SecureSocketOptions.SslOnConnect ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
			var socket = new StreamSocket ();

			try {
				cancellationToken.ThrowIfCancellationRequested ();
				socket.ConnectAsync (new HostName (host), port.ToString (), protection)
					.AsTask (cancellationToken)
					.GetAwaiter ()
					.GetResult ();
			} catch {
				socket.Dispose ();
				throw;
			}

			stream = new DuplexStream (socket.InputStream.AsStreamForRead (0), socket.OutputStream.AsStreamForWrite (0));
#endif

			if (stream.CanTimeout) {
				stream.WriteTimeout = timeout;
				stream.ReadTimeout = timeout;
			}

			ProtocolLogger.LogConnect (uri);

			Stream = new SmtpStream (stream, socket, ProtocolLogger);

			try {
				// read the greeting
				response = Stream.ReadResponse (cancellationToken);

				if (response.StatusCode != SmtpStatusCode.ServiceReady)
					throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

				// Send EHLO and get a list of supported extensions
				Ehlo (cancellationToken);

				if (options == SecureSocketOptions.StartTls && (capabilities & SmtpCapabilities.StartTLS) == 0)
					throw new NotSupportedException ("The SMTP server does not support the STARTTLS extension.");

				if (starttls && (capabilities & SmtpCapabilities.StartTLS) != 0) {
					response = SendCommand ("STARTTLS", cancellationToken);
					if (response.StatusCode != SmtpStatusCode.ServiceReady)
						throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

#if !NETFX_CORE
					var tls = new SslStream (stream, false, ValidateRemoteCertificate);
					tls.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
					Stream.Stream = tls;
#else
					socket.UpgradeToSslAsync (SocketProtectionLevel.Tls12, new HostName (host))
						.AsTask (cancellationToken)
						.GetAwaiter ()
						.GetResult ();
#endif

					// Send EHLO again and get the new list of supported extensions
					Ehlo (cancellationToken);
				}

				connected = true;
			} catch {
				Stream.Dispose ();
				Stream = null;
				throw;
			}

			OnConnected ();
		}
コード例 #36
0
ファイル: XHRProxy.cs プロジェクト: El-Ruaan/titanium_mobile
		private async void requestError(DataWriter writer, StreamSocket socket, string status, string message = "") {
			writer.WriteString("HTTP/1.0 " + status + "\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n" + message);
			await writer.StoreAsync();
			socket.Dispose();
		}
コード例 #37
0
ファイル: MainPage.xaml.cs プロジェクト: MxAR/SGP
        private async void ConnectToDevice(PeerInformation peer)
        {
            if (_socket != null)
            {
                // Disposing the socket with close it and release all resources associated with the socket
                _socket.Dispose();
            }

            try
            {
                _socket = new StreamSocket();
                string serviceName = (String.IsNullOrWhiteSpace(peer.ServiceName)) ? tbServiceName.Text : peer.ServiceName;

                // Note: If either parameter is null or empty, the call will throw an exception
                await _socket.ConnectAsync(peer.HostName, serviceName);

                // If the connection was successful, the RemoteAddress field will be populated
               MessageBox.Show(String.Format(AppResources.Msg_ConnectedTo, _socket.Information.RemoteAddress.DisplayName));
            }
            catch (Exception ex)
            {
                // In a real app, you would want to take action dependent on the type of 
                // exception that occurred.
                MessageBox.Show(ex.Message);

                _socket.Dispose();
                _socket = null;
            }
        }
コード例 #38
0
        private void Connect(StreamSocket socket, AmqpTcpEndpoint endpoint, int timeout)
        {
            IAsyncAction ar = null;
            try
            {
                var cts = new CancellationTokenSource();
                if (this.defaultTimeout.HasValue)
                    cts.CancelAfter(this.defaultTimeout.Value);

                ar = socket.ConnectAsync(new HostName(endpoint.HostName), endpoint.Port.ToString(), SocketProtectionLevel.PlainSocket);
                if (!ar.AsTask(cts.Token).Wait(timeout))
                {
                    socket.Dispose();
                    throw new TimeoutException("Connection to " + endpoint + " timed out");
                }
                ar.GetResults();
            }
            catch (ArgumentException e)
            {
                throw new ConnectFailureException("Connection failed", e);
            }
            catch (Exception e)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                throw new ConnectFailureException("Connection failed", e);
            }
            finally
            {
                if (ar != null)
                {
                    ar.Close();
                }
            }
        }
コード例 #39
0
ファイル: Connection.cs プロジェクト: spinglass/PerformantApp
        private async Task<StreamSocket> OpenSocketAsync()
        {
            StreamSocket socket = null;

            try
            {
                socket = new StreamSocket();
                await socket.ConnectAsync(m_HostName, m_Port.ToString());

                m_Sender.Open(socket.InputStream, socket.OutputStream);

                // Handshake with the server
                if (await m_Sender.Handshake())
                {
                    Debug.WriteLine("[Connection.OpenSocket] Connected to server opened");
                }
                else
                {
                    m_Sender.Close();
                    socket.Dispose();
                    socket = null;
                }
            }
            catch (Exception)
            {
                socket = null;
            }

            return socket;
        }
コード例 #40
0
ファイル: RTSocketConnection.cs プロジェクト: dmetzgar/wcf
 protected override async Task<IConnection> CreateConnectionAsync(IPAddress address, int port)
 {
     StreamSocket socket = null;
     try
     {
         socket = new StreamSocket();
         socket.Control.OutboundBufferSizeInBytes = (uint)_connectionBufferPool.BufferSize;
         await socket.ConnectAsync(new HostName(address.ToString()), port.ToString()).AsTask();
         return new RTSocketConnection(socket, _connectionBufferPool);
     }
     catch (Exception exception)
     {
         socket.Dispose();
         if (RTSocketError.GetStatus(exception.HResult) != SocketErrorStatus.Unknown)
         {
             throw new SocketException(exception.HResult & 0x0000FFFF);
         }
         throw;
     }
 }
コード例 #41
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            this.serviceDeferral = taskInstance.GetDeferral();
            try {
                var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
                if (triggerDetails != null && triggerDetails.Name == "CortanaCommandService")
                {

                    voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                    var voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
                    Debug.WriteLine(voiceCommand.CommandName);

                    MainViewModel viewModel = new MainViewModel();
                    var vm = await DataLoadAsync();
                    if (vm != null)
                    {
                        viewModel = vm;
                    }

                    var cols = voiceCommand.CommandName.Split('_');
                    var commandName = cols[0];
                    var stateName = cols[1];

                    var commandViewModel = viewModel.CommandList.First(q => q.Name == commandName);
                    
                    commandViewModel.CurrentStateNum++;
                    var stateViewModel = commandViewModel.StateList.ElementAt(commandViewModel.CurrentStateNum - 1);
                    if (commandViewModel.CurrentStateNum>=commandViewModel.StateList.Count)
                    {
                        commandViewModel.CurrentStateNum = 0;
                    }

                    if(stateViewModel is SuccessStateViewModel)
                    {
                        var state = stateViewModel as SuccessStateViewModel;
                        if (string.IsNullOrEmpty(state.Utterance))
                        {
                            state.Utterance = "";
                        }
                        var message = new VoiceCommandUserMessage();
                        message.SpokenMessage = state.Utterance;
                        message.DisplayMessage = state.Utterance;
                        var response = VoiceCommandResponse.CreateResponse(message);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else if(stateViewModel is ScriptStateViewModel)
                    {
                        var state = stateViewModel as ScriptStateViewModel;
                        if (!string.IsNullOrEmpty(state.Script))
                        {
                            try {
                                ConnectionData connectionData = new ConnectionData();
                                connectionData.AcceptPass = viewModel.PassCode;
                                connectionData.Script = state.Script.Replace("\n", ";").Replace("\r", "").Replace("\t", "");
                                string json = JsonConvert.SerializeObject(connectionData);
                                var byteData = Encoding.UTF8.GetBytes(json);
                                StreamSocket socket = new StreamSocket();

                                await socket.ConnectAsync(new HostName("127.0.0.1"), SettingManager.ServerPort);
                                var writer = new DataWriter(socket.OutputStream);
                                writer.WriteBytes(byteData);
                                await writer.StoreAsync();
                                await writer.FlushAsync();
                                writer.Dispose();
                                socket.Dispose();
                                
                            }
                            catch (Exception)
                            {
                                var errorMsg = new VoiceCommandUserMessage();
                                string msg = "スクリプトの実行を試みましたがサーバーが起動してませんでした";
                                errorMsg.SpokenMessage = msg;
                                errorMsg.DisplayMessage = msg;
                                var errorResponse = VoiceCommandResponse.CreateResponse(errorMsg);
                                await voiceServiceConnection.ReportFailureAsync(errorResponse);
                                return;
                            }
                        }


                        if (string.IsNullOrEmpty(state.Utterance))
                        {
                            state.Utterance = "";
                        }
                        var message = new VoiceCommandUserMessage();
                        message.SpokenMessage = state.Utterance;
                        message.DisplayMessage = state.Utterance;
                        var response = VoiceCommandResponse.CreateResponse(message);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }

                    await DataSaveAsync(viewModel);
                }

            }catch(Exception e)
            {
                var message = new VoiceCommandUserMessage();
                message.SpokenMessage = "何かしらのエラーが起きました";
                message.DisplayMessage = e.Message;
                var response = VoiceCommandResponse.CreateResponse(message);
                await voiceServiceConnection.ReportSuccessAsync(response);

                var toast = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText01);
                ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toast));
            }
            

            this.serviceDeferral.Complete();
        }
コード例 #42
0
        private async void HandleRequest(StreamSocket socket)
        {
            var reader = new DataReader(socket.InputStream) { InputStreamOptions = InputStreamOptions.Partial };
            var writer = new DataWriter(socket.OutputStream) { UnicodeEncoding = UnicodeEncoding.Utf8 };

            var acceptedRequest = new AcceptedRequest();
            await acceptedRequest.AcceptRequest(reader);

            string response;
            try
            {
                response = HttpResponseHelper.ResponseString(
                    HttpStatusCode.OK, 
                    this.automator.ProcessCommand(acceptedRequest.Content));
            }
            catch (NotImplementedException ex)
            {
                response = HttpResponseHelper.ResponseString(HttpStatusCode.NotImplemented, ex.Message);
            }

            writer.WriteString(response);
            await writer.StoreAsync();

            socket.Dispose();

            if (this.automator.DoAfterResponseOnce == null)
            {
                return;
            }

            var localDoAfterResponseOnce = this.automator.DoAfterResponseOnce;
            this.automator.DoAfterResponseOnce = null;

            localDoAfterResponseOnce();
        }
コード例 #43
0
        async private void ConnectDevice_Click(object sender, RoutedEventArgs e)
        {
            DeviceInformation DeviceInfo = ((PairedDeviceInfo)ConnectDevices.SelectedItem).DeviceInfo;// await DeviceInformation.CreateFromIdAsync(this.TxtBlock_SelectedID.Text);
            bool success = true;
            try
            {
                _service = await RfcommDeviceService.FromIdAsync(DeviceInfo.Id);

                if (_socket != null)
                {
                    // Disposing the socket with close it and release all resources associated with the socket
                    _socket.Dispose();
                }

                _socket = new StreamSocket();
                try { 
                    // Note: If either parameter is null or empty, the call will throw an exception
                    await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);
                }
                catch (Exception ex)
                {
                        success = false;
                        System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message);
                }
                // If the connection was successful, the RemoteAddress field will be populated
                if (success)
                {
                    _Mode = Mode.JustConnected;
                    this.buttonDisconnect.IsEnabled = true;
                    this.buttonSend.IsEnabled = true;
                    this.buttonStartRecv.IsEnabled = true;
                    this.buttonStopRecv.IsEnabled = false;
                    string msg = String.Format("Connected to {0}!", _socket.Information.RemoteAddress.DisplayName);
                    //MessageDialog md = new MessageDialog(msg, Title);
                    string lcdMsg = "~C" + "BT Serial Connected";
                    lcdMsg += "~" + ArduinoLCDDisplay.LCD.CMD_DISPLAY_LINE_2_CH + "PressBack/Select   ";
                    Send(lcdMsg);
                    this.buttonStartRecv.IsEnabled = false;
                    this.buttonStopRecv.IsEnabled = true;
                    Listen();
                    System.Diagnostics.Debug.WriteLine(msg);
                    //await md.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Overall Connect: " +ex.Message);
                _socket.Dispose();
                _socket = null;
            }
        }
コード例 #44
0
        //------------------------------------------------------------------------------------------------------------------------
        protected override void onClose(string Message)
        {
            try
            {
                base.onClose(Message);

                //close all
                try
                {
                    if (streamIn != null)
                    {
#if NETFX
                        TaskEx.RunSafe(streamIn.Close, AssertException: false)?.Wait(1000);
#endif
                        TaskEx.RunSafe(streamIn.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }

                try
                {
                    if (streamOut != null)
                    {
#if NETFX
                        TaskEx.RunSafe(streamOut.Close, AssertException: false)?.Wait(1000);
#endif
                        TaskEx.RunSafe(streamOut.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }

#if NETFX
                try
                {
                    if (netstream != null)
                    {
                        TaskEx.RunSafe(netstream.Close, AssertException: false)?.Wait(1000);
                        TaskEx.RunSafe(netstream.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }
#endif
                try
                {
#if NETFX
                    if (_sock?.Connected == true)
                    {
                        TaskEx.RunSafe(() => _sock?.Disconnect(false), AssertException: false)?.Wait(1000);
                    }

                    TaskEx.RunSafe(() => _sock?.Close(3), AssertException: false)?.Wait(5000);
#endif
                    TaskEx.RunSafe(() => _sock?.Dispose(), AssertException: false)?.Wait(1000);
                }
                catch { }

                //null them
                streamIn  = null;
                streamOut = null;
#if NETFX
                netstream = null;
#endif
                _sock = null;
            }
            catch (Exception ex) { DebugEx.Assert(ex, "YPC (" + Name + ") Exception while disconnecting"); }
        }
コード例 #45
0
ファイル: Server.cs プロジェクト: sm6uax/plegma
        //------------------------------------------------------------------------------------------------------------------------
        public void Stop(bool CloseAllChannels = false)
        {
            try
            {
                lock (this)
                {
                    //close all channels
                    if (CloseAllChannels)
                    {
                        var channelsToClose = _Channels.ToArray();
                        TaskEx.RunSafe(() =>
                        {
                            var po = new ParallelOptions()
                            {
                                MaxDegreeOfParallelism = 8
                            };

                            Parallel.ForEach(channelsToClose, po, c =>
                            {
                                { try { c.Close("Server stopped"); } catch (Exception ex) { DebugEx.TraceErrorException(ex, "Error while closing channel"); } };
                            });
                        });
                    }

                    //update flag
                    if (!_IsRunning)
                    {
                        return;
                    }
                    else
                    {
                        _IsRunning = false;
                    }

                    //close my socket
                    try
                    {
                        if (sock != null)
                        {
#if NETFX
                            try { sock.Close(); } catch { }
#endif
                            try { sock.Dispose(); } catch { }
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugEx.TraceErrorException(ex);
                    }
                    sock = null;

                    //wait for task finish
#if NETFX
                    PortListener?.Join(1000);
#elif UNIVERSAL
                    PortListener?.Wait(1000);
#endif
                    PortListener = null;
                }
            }
            catch (Exception ex)
            {
                DebugEx.Assert(ex, "YPChannel Server Stop() failed");
            }
        }
コード例 #46
0
ファイル: Server.cs プロジェクト: sm6uax/plegma
        //------------------------------------------------------------------------------------------------------------------------
        void HandleNewConnection(Socket newsocket)
        {
            try
            {
                #region check reconnection throttle
                try
                {
                    //setup socket
                    newsocket.ReceiveTimeout = -1;
                    newsocket.SendTimeout    = 60 * 1000;

#if NETFX
                    var re = newsocket.RemoteEndPoint.GetIPAddress().ToStringInvariant();
#elif UNIVERSAL
                    var re = newsocket.Information.RemoteAddress.ToStringInvariant();
#endif
                    //filtering
                    if (OnNewSocketConnectionFilter != null && OnNewSocketConnectionFilter(this, re) == false)
                    {
#if NETFX
                        try { newsocket.Close(); } catch { }
#endif
                        try { newsocket.Dispose(); } catch { }
                        DebugEx.TraceWarning("Connection from " + re + " closed from filter");
                        return;
                    }

                    if (IsReconnectionThrottleEnabled && re != "127.0.0.1" && re != "localhost") //no reconnection throttle for localhost connections
                    {
                        var rbe = reconnectThrottleBookKeeper.TryGetOrDefault(re);
                        if (rbe == null)
                        {
                            rbe = new ReconnectionBookkeepEntry()
                            {
                                ConnectionTimestamp = DateTime.Now + TimeSpan.FromMilliseconds(100),
                                Connections         = 1,
                            };
                            reconnectThrottleBookKeeper.ForceAdd(re, rbe);
                        }
                        else
                        {
                            if (++rbe.Connections > ReconnectionThrottleAfterConnectionCount)
                            {
                                var elapsed = DateTime.Now - rbe.ConnectionTimestamp;
                                if (elapsed < ReconnectionThrottleTimeout)
                                {
#if NETFX
                                    try { newsocket.Close(); } catch { }
#endif
                                    try { newsocket.Dispose(); } catch { }
                                    DebugEx.TraceWarning("Connection from " + re + " closed due to reconnection throttle (" + elapsed.Seconds + " sec)");
                                    return;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex) { DebugEx.TraceWarning(ex, "YPServer Reconnection throttle exception"); }

                //cleanup old entries
                reconnectThrottleBookKeeper.RemoveWhere(e => DateTime.Now - e.Value.ConnectionTimestamp > ReconnectionThrottleTimeout);
                #endregion

                //start task new connection
                Task.Run(() =>
                {
                    ServerChannel channel = null;
                    string channelKey     = null;

                    Thread.Sleep(MathTools.GetRandomNumber(1, 100));
                    try
                    {
                        //check
#if NETFX
                        if (!newsocket.Connected)
                        {
                            DebugEx.TraceWarning("YPServer newsocket not connected?");
                            try { newsocket.Close(); } catch { }
                            return;
                        }
#endif
                        //create channel
                        var con = ChannelConstructor;
                        channel = con == null ? new ServerChannel(this, Protocols, SupportedChannelSerializationModes, PreferredChannelSerializationModes, newsocket) : con(Protocols, newsocket);
                        if (channel == null)
                        {
                            DebugEx.Assert("Could not create channel");
#if NETFX
                            try { newsocket.Close(); } catch { }
#endif
                            try { newsocket.Dispose(); } catch { }
                            return;
                        }

                        //add to set
                        lock (_Channels)
                        {
                            //generate unique key
                            while (IssuedKeys.ContainsKey(channelKey = MathTools.GenerateRandomAlphaNumericString(64)))
                            {
                                ;
                            }
                            //set on channel
                            channel._ChannelKey = channelKey;
                            //add to lookups
                            _Channels.Add(channel);
                            IssuedKeys.Add(channelKey, channel);
                        }

                        //start task timeout monitor
                        bool setupFinished = false;
                        Task.Run(() =>
                        {
                            try
                            {
                                //wait
                                Thread.Sleep(30000);
                                //check
                                if (!setupFinished)
                                {
                                    DebugEx.TraceLog($"ServerChannel setup timeout ({channel})");
                                    try { channel.Close("ServerChannel setup timeout"); } catch { }
#if NETFX
                                    try { newsocket?.Close(); } catch { }
#endif
                                    try { newsocket?.Dispose(); } catch { }

                                    //remove from lookups
                                    lock (_Channels)
                                    {
                                        if (channel != null)
                                        {
                                            _Channels.Remove(channel);
                                        }
                                        if (channelKey != null)
                                        {
                                            IssuedKeys.Remove(channelKey);
                                        }
                                    }
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                DebugEx.Assert(ex, $"Unhandled exception ({channel})");
#if NETFX
                                try { newsocket?.Close(); } catch { }
#endif
                                try { newsocket?.Dispose(); } catch { }

                                //remove from lookups
                                lock (_Channels)
                                {
                                    if (channel != null)
                                    {
                                        _Channels.Remove(channel);
                                    }
                                    if (channelKey != null)
                                    {
                                        IssuedKeys.Remove(channelKey);
                                    }
                                }
                                return;
                            }
                        });

                        //set serializer
                        channel.MsgPack = MsgPackSerializer;

                        //setup channel socket
                        if (channel.SetupServerSocket() == false)
                        {
#if NETFX
                            try { newsocket?.Close(); } catch { }
#endif
                            try { newsocket?.Dispose(); } catch { }

                            //remove from lookups
                            lock (_Channels)
                            {
                                if (channel != null)
                                {
                                    _Channels.Remove(channel);
                                }
                                if (channelKey != null)
                                {
                                    IssuedKeys.Remove(channelKey);
                                }
                            }
                            return;
                        }

                        //mark setup finish
                        setupFinished = true;

                        //call event
                        OnNewChannel?.Invoke(this, channel);

                        //start heartbeat
                        channel.Start();
                    }
                    catch (Exception ex)
                    {
                        DebugEx.Assert(ex, "YPServer: Failed setting up new connection for " + channel);
#if NETFX
                        try { newsocket.Close(); } catch { }
#endif
                        try { newsocket.Dispose(); } catch { }

                        //remove from lookups
                        lock (_Channels)
                        {
                            if (channel != null)
                            {
                                _Channels.Remove(channel);
                            }
                            if (channelKey != null)
                            {
                                IssuedKeys.Remove(channelKey);
                            }
                        }
                        return;
                    }
                });
            }
            catch (Exception ex)
            {
                DebugEx.Assert(ex, "YPChannel server setup new connection error");
            }
        }
コード例 #47
0
ファイル: Login.xaml.cs プロジェクト: seb2020/CloudWave
        public async void validateCertificate()
        {
            // Define some variables and set values
            StreamSocket clientSocket = new StreamSocket();

            System.Uri uri = new System.Uri(TextBox_url.Text);

            // get the port
            int port = uri.Port;

            // get the host name (my.domain.com)
            string host = uri.Host;

            // get the protocol
            string protocol = uri.Scheme;

            // get everything before the query:
            string cleanURL = uri.GetComponents(UriComponents.Host, UriFormat.UriEscaped);

            HostName serverHost = new HostName(cleanURL);
            string serverServiceName = "https";

            // Try to connect to contoso using HTTPS (port 443)
            try
            {

                // Call ConnectAsync method with SSL
                await clientSocket.ConnectAsync(serverHost, serverServiceName, SocketProtectionLevel.Tls12);

                Debug.WriteLine("Connected");

                loginRequestUser(TextBox_login.Text, PasswordBox_Password.Password, TextBox_url.Text, "auth-token");
        
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    if (GlobalVariables.IsDebugMode == true)
                    {
                        App.logger.log(LogLevel.critical, "Connect failed with error: " + exception.Message);
                    }
                }

                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.CertificateExpired)
                {
                   if (GlobalVariables.IsDebugMode == true)
                   {
                       App.logger.log(LogLevel.critical, "Connect failed with error: " + exception.Message);
                   }
                   if (MessageBox.Show(AppResources.Certificate_Error_Expired, AppResources.Certificate_Error_Title, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                   {
                       CertificateValidateByUser = true;
                   }
                }
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.CertificateRevoked)
                {
                   if (GlobalVariables.IsDebugMode == true)
                   {
                       App.logger.log(LogLevel.critical, "Connect failed with error: " + exception.Message);
                   }
                   if (MessageBox.Show(AppResources.Certificate_Error_Revoked, AppResources.Certificate_Error_Title, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                   {
                      CertificateValidateByUser = true;                     
                   }
                }
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.CertificateIsInvalid)
                {
                   if (GlobalVariables.IsDebugMode == true)
                   {
                        App.logger.log(LogLevel.critical, "Connect failed with error: " + exception.Message);
                   }
                   if (MessageBox.Show(AppResources.Certificate_Error_Invalid, AppResources.Certificate_Error_Title, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                   {
                       CertificateValidateByUser = true;   
                   }
                }
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.CertificateUntrustedRoot)
                {
                   if (GlobalVariables.IsDebugMode == true)
                   {
                       App.logger.log(LogLevel.critical, "Connect failed with error: " + exception.Message);
                   }
                   if (MessageBox.Show(AppResources.Certificate_Error_UntrustedRoot, AppResources.Certificate_Error_Title, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                   {
                       CertificateValidateByUser = true;   
                   }
                }
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.CertificateCommonNameIsIncorrect)
                {
                   if (GlobalVariables.IsDebugMode == true)
                   {
                       App.logger.log(LogLevel.critical, "Connect failed with error: " + exception.Message);
                   }
                   if( MessageBox.Show(AppResources.Certificate_Error_CNMissmatch, AppResources.Certificate_Error_Title, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                   {
                       CertificateValidateByUser = true;   
                   }
                }

                clientSocket.Dispose();
                clientSocket = null;

                if (CertificateValidateByUser == true)
                {
                    loginRequestUser(TextBox_login.Text, PasswordBox_Password.Password, TextBox_url.Text, "auth-token");
                }
                else
                {
                    SetProgressIndicator(false);
                    MessageBox.Show(AppResources.Login_Error_SSL_NotValidate_Content, AppResources.Login_Error_SSL_NotValidate_Title, MessageBoxButton.OK);
                }
            }
        }
コード例 #48
0
ファイル: ImapClient.cs プロジェクト: yukine/MailKit
		/// <summary>
		/// Establish a connection to the specified IMAP server.
		/// </summary>
		/// <remarks>
		/// <para>Establishes a connection to the specified IMAP or IMAP/S server.</para>
		/// <para>If the <paramref name="port"/> has a value of <c>0</c>, then the
		/// <paramref name="options"/> parameter is used to determine the default port to
		/// connect to. The default port used with <see cref="SecureSocketOptions.SslOnConnect"/>
		/// is <c>993</c>. All other values will use a default port of <c>143</c>.</para>
		/// <para>If the <paramref name="options"/> has a value of
		/// <see cref="SecureSocketOptions.Auto"/>, then the <paramref name="port"/> is used
		/// to determine the default security options. If the <paramref name="port"/> has a value
		/// of <c>993</c>, then the default options used will be
		/// <see cref="SecureSocketOptions.SslOnConnect"/>. All other values will use
		/// <see cref="SecureSocketOptions.StartTlsWhenAvailable"/>.</para>
		/// <para>Once a connection is established, properties such as
		/// <see cref="AuthenticationMechanisms"/> and <see cref="Capabilities"/> will be
		/// populated.</para>
		/// </remarks>
		/// <example>
		/// <code language="c#" source="Examples\ImapExamples.cs" region="DownloadMessages"/>
		/// </example>
		/// <param name="host">The host name to connect to.</param>
		/// <param name="port">The port to connect to. If the specified port is <c>0</c>, then the default port will be used.</param>
		/// <param name="options">The secure socket options to when connecting.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="host"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="port"/> is not between <c>0</c> and <c>65535</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// The <paramref name="host"/> is a zero-length string.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// The <see cref="ImapClient"/> is already connected.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// <paramref name="options"/> was set to
		/// <see cref="MailKit.Security.SecureSocketOptions.StartTls"/>
		/// and the IMAP server does not support the STARTTLS extension.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// An IMAP protocol error occurred.
		/// </exception>
		public override void Connect (string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (host == null)
				throw new ArgumentNullException ("host");

			if (host.Length == 0)
				throw new ArgumentException ("The host name cannot be empty.", "host");

			if (port < 0 || port > 65535)
				throw new ArgumentOutOfRangeException ("port");

			CheckDisposed ();

			if (IsConnected)
				throw new InvalidOperationException ("The ImapClient is already connected.");

			Stream stream;
			bool starttls;
			Uri uri;

			ComputeDefaultValues (host, ref port, ref options, out uri, out starttls);

#if !NETFX_CORE
			var ipAddresses = Dns.GetHostAddresses (host);
			Socket socket = null;

			for (int i = 0; i < ipAddresses.Length; i++) {
				socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

				try {
					cancellationToken.ThrowIfCancellationRequested ();
					socket.Connect (ipAddresses[i], port);
					break;
				} catch (OperationCanceledException) {
					socket.Dispose ();
					throw;
				} catch {
					socket.Dispose ();

					if (i + 1 == ipAddresses.Length)
						throw;
				}
			}

			if (socket == null)
				throw new IOException (string.Format ("Failed to resolve host: {0}", host));
			
			engine.Uri = uri;

			if (options == SecureSocketOptions.SslOnConnect) {
				var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
				ssl.AuthenticateAsClient (host, ClientCertificates, DefaultSslProtocols, true);
				stream = ssl;
			} else {
				stream = new NetworkStream (socket, true);
			}
#else
			var protection = options == SecureSocketOptions.SslOnConnect ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
			socket = new StreamSocket ();

			try {
				cancellationToken.ThrowIfCancellationRequested ();
				socket.ConnectAsync (new HostName (host), port.ToString (), protection)
					.AsTask (cancellationToken)
					.GetAwaiter ()
					.GetResult ();
			} catch {
				socket.Dispose ();
				socket = null;
				throw;
			}

			stream = new DuplexStream (socket.InputStream.AsStreamForRead (0), socket.OutputStream.AsStreamForWrite (0));
			engine.Uri = uri;
#endif

			if (stream.CanTimeout) {
				stream.WriteTimeout = timeout;
				stream.ReadTimeout = timeout;
			}

			ProtocolLogger.LogConnect (uri);

			engine.Connect (new ImapStream (stream, socket, ProtocolLogger), cancellationToken);

			try {
				// Only query the CAPABILITIES if the greeting didn't include them.
				if (engine.CapabilitiesVersion == 0)
					engine.QueryCapabilities (cancellationToken);
				
				if (options == SecureSocketOptions.StartTls && (engine.Capabilities & ImapCapabilities.StartTLS) == 0)
					throw new NotSupportedException ("The IMAP server does not support the STARTTLS extension.");
				
				if (starttls && (engine.Capabilities & ImapCapabilities.StartTLS) != 0) {
					var ic = engine.QueueCommand (cancellationToken, null, "STARTTLS\r\n");

					engine.Wait (ic);

					if (ic.Response == ImapCommandResponse.Ok) {
#if !NETFX_CORE
						var tls = new SslStream (stream, false, ValidateRemoteCertificate);
						tls.AuthenticateAsClient (host, ClientCertificates, DefaultSslProtocols, true);
						engine.Stream.Stream = tls;
#else
						socket.UpgradeToSslAsync (SocketProtectionLevel.Tls12, new HostName (host))
							.AsTask (cancellationToken)
							.GetAwaiter ()
							.GetResult ();
#endif

						// Query the CAPABILITIES again if the server did not include an
						// untagged CAPABILITIES response to the STARTTLS command.
						if (engine.CapabilitiesVersion == 1)
							engine.QueryCapabilities (cancellationToken);
					} else if (options == SecureSocketOptions.StartTls) {
						throw ImapCommandException.Create ("STARTTLS", ic);
					}
				}
			} catch {
				engine.Disconnect ();
				throw;
			}

			engine.Disconnected += OnEngineDisconnected;
			OnConnected ();
		}
コード例 #49
0
        async private void Connect(DeviceInformation DeviceInfo)
        {
            System.Diagnostics.Debug.WriteLine("Connect");

            bool success = true;
            try
            {
                _service = await RfcommDeviceService.FromIdAsync(DeviceInfo.Id);

                if (_socket != null)
                {
                    // Disposing the socket with close it and release all resources associated with the socket
                    _socket.Dispose();
                }

                _socket = new StreamSocket();
                try
                {
                    // Note: If either parameter is null or empty, the call will throw an exception
                    await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);
                }
                catch (Exception ex)
                {
                    success = false;
                    System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message);
                }
                // If the connection was successful, the RemoteAddress field will be populated
                if (success)
                {
                    this.DoButton.IsEnabled = true;
                    string msg = String.Format("Connected to {0}!", _socket.Information.RemoteAddress.DisplayName);
                    System.Diagnostics.Debug.WriteLine(msg);
                    this.NowConnectedDevice = DeviceInfo;
                    //Listen(); If listening works at all, output is not handle yet.
                }
                else
                {
                    this.DoButton.IsEnabled = false;
                    this.NowConnectedDevice = null;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message);
                _socket.Dispose();
                _socket = null;
                this.NowConnectedDevice = null;
            }
        }