當前位置: 首頁>>代碼示例>>C#>>正文


C# StreamSocket.ConnectAsync方法代碼示例

本文整理匯總了C#中Windows.Networking.Sockets.StreamSocket.ConnectAsync方法的典型用法代碼示例。如果您正苦於以下問題:C# StreamSocket.ConnectAsync方法的具體用法?C# StreamSocket.ConnectAsync怎麽用?C# StreamSocket.ConnectAsync使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Windows.Networking.Sockets.StreamSocket的用法示例。


在下文中一共展示了StreamSocket.ConnectAsync方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: SendMessage

 public async void SendMessage(string msg)
 {
     HostName hostName;
     try
     {
         hostName = new HostName("localhost");
     }
     catch (ArgumentException)
     {
         return;
     }
     StreamSocket socket;
     try
     {
         using (socket = new StreamSocket())
         {
             await socket.ConnectAsync(hostName, port2);
             //CoreApplication.Properties.Add("connected", null);
             DataWriter dw = new DataWriter(socket.OutputStream);
             dw.WriteString(msg);
             await dw.StoreAsync();
         }
     }
     catch
     {
         //break;
     }
 }
開發者ID:ballance,項目名稱:MetroTorrent,代碼行數:28,代碼來源:ServerCommunicator.cs

示例2: ConnectTo

 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;
     }
 }
開發者ID:ReCaD2016,項目名稱:ReCaD-2.0,代碼行數:35,代碼來源:AgentConnection.cs

示例3: ConnectToSignalingServer

        public ConnectionStatus ConnectToSignalingServer(ConnectionOwner connectionOwner)
        {
            try
            {
                SignaledPeerData.Reset();
                SignalingStatus.Reset();
                SignaledRelayMessages.Reset();

                var socket = new StreamSocket();
                socket.EnableTransferOwnership(Guid.Parse(connectionOwner.OwnerId),
                    SocketActivityConnectedStandbyAction.Wake);
                socket.ConnectAsync(new HostName(SignalingSettings.SignalingServerHost),
                    SignalingSettings.SignalingServerPort, SocketProtectionLevel.PlainSocket)
                    .AsTask()
                    .Wait();
                socket.TransferOwnership(SignalingSocketOperation.SignalingSocketId);
                return new ConnectionStatus
                {
                    IsConnected = true
                };
            }
            catch (Exception exception)
            {
                return new ConnectionStatus
                {
                    IsConnected = false
                };
            }
        }
開發者ID:hungdluit,項目名稱:ChatterBox,代碼行數:29,代碼來源:SignalingSocketService.cs

示例4: TryConnect

        private async void TryConnect ( )
        {
            if ( connectList.SelectedItem != null )
            {
                try
                {
                    PeerFinder.Start(  );
                    PeerFinder.AlternateIdentities[ "Bluetooth:Paired" ] = "";
                    var pairedDevices = await PeerFinder.FindAllPeersAsync();

                    UpdateStatus( "Connecting to selected device: " + pairedDevices[ connectList.SelectedIndex ].DisplayName );

                    socket = new StreamSocket(); // Create socket.
                    await socket.ConnectAsync( pairedDevices[ connectList.SelectedIndex ].HostName, "1" ); // Connect to device using socket.

                    connected = true;
                    textblockDevice.Text = "Connected to " + pairedDevices[ connectList.SelectedIndex ].DisplayName;
                    UpdateStatus( "success!" );

                    WaitForData( socket );

                    Write( "#p" ); // First ping to test connection.
                }
                catch ( Exception ex )
                {
                    UpdateStatus( "Error: " + ex.Message + "," + ex.StackTrace );
                }
            }
            else
            {
                UpdateStatus( "Please select a device." );
            }
        }
開發者ID:bryanschremp,項目名稱:BT_LED_Control,代碼行數:33,代碼來源:MainPage.xaml.cs

示例5: Connect

        public async Task Connect()
        {
            PeerFinder.AlternateIdentities["Bluetooth:SDP"] = ServiceGUID.ToString();
            var peers = await PeerFinder.FindAllPeersAsync();

            foreach (var p in peers)
            {
                var h = p.ServiceName;
            }

            // TODO: obviously list these instead of taking the first
            var peer = peers.FirstOrDefault();

            if (peer != null)
            {
                var socket = new StreamSocket();
                try
                {
                    // default service name?
                    await socket.ConnectAsync(peer.HostName, ServiceName);

                    var connection = new DuplexConnection(socket);
                    var device = new BluetoothDevice(peer.DisplayName, peer.HostName, peer.ServiceName);

                    if (ConnectionEstablished != null)
                    {
                        ConnectionEstablished(this, new ClientConnectedEventArgs(device, connection));
                    }
                } 
                catch (Exception ex)
                {
                    
                }
            }
        }
開發者ID:peterdn,項目名稱:Geomoir,代碼行數:35,代碼來源:BluetoothClient.cs

示例6: CheckServerAddressWP

        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;
        }
開發者ID:cephalin,項目名稱:ContosoMoments,代碼行數:33,代碼來源:Utils.cs

示例7: Connect

 /// <summary>
 /// Attempt to create a tcp connection to a certain host
 /// </summary>
 /// <param name="remoteAddress">Address of the remote host</param>
 /// <param name="connectionTimeout">Time (in milliseconds) that defines how long we should attempt to connect to the other party</param>
 /// <returns>Returns a StreamSocket to the remote host</returns>
 private async Task<StreamSocket> Connect(string remoteAddress, int connectionTimeout)
 {
     StreamSocket streamSocket = new StreamSocket();
     // Make sure a timeout occurs (otherwise it will try to connect forever)
     CancellationTokenSource cts = new CancellationTokenSource();
     try
     {
         cts.CancelAfter(connectionTimeout);
         // Try to connect to the remote address
         await streamSocket.ConnectAsync(new HostName(remoteAddress), this.port).AsTask(cts.Token);
         return streamSocket;
     }
     catch (TaskCanceledException ex)
     {
         // TaskCanceledException will be thrown when the timeout has passed. 
         // Now throw our own exception
         throw new ConnectionTimedOutException("Could not create connection with host " + remoteAddress + " within the given time-out period of " + connectionTimeout + "ms. ");
     }
     catch (System.Exception ex)
     {
         // Catch any other exception too
         System.Diagnostics.Debug.WriteLine("Exception occured in TCPSocketClient.Connect: " + ex);
         throw;
     }
 }
開發者ID:svdvonde,項目名稱:bachelorproef,代碼行數:31,代碼來源:TCPSocketClient.cs

示例8: ConnectAsync

        public static async Task<bool> ConnectAsync()
        {
            if (imageComparisonServer != null)
                return true;
			
            try
            {
                imageComparisonServer = new StreamSocket();
                await imageComparisonServer.ConnectAsync(new HostName(ParadoxImageServerHost), ParadoxImageServerPort.ToString());
			
                // Send initial parameters
                using (var memoryStream = new MemoryStream())
                {
                    var binaryWriter = new BinaryWriter(memoryStream);
                    ImageTestResultConnection.Write(binaryWriter);

                    var dataWriter = new DataWriter(imageComparisonServer.OutputStream);
                    dataWriter.WriteBytes(memoryStream.ToArray());
                    await dataWriter.StoreAsync();
                    await dataWriter.FlushAsync();
                    dataWriter.DetachStream();
                }

                return true;
            }
            catch (Exception)
            {
                imageComparisonServer = null;
			
                return false;
            }
        }
開發者ID:Powerino73,項目名稱:paradox,代碼行數:32,代碼來源:ImageTester.Runtime.cs

示例9: RefreshLogsTapped

		private async void RefreshLogsTapped(object sender, TappedRoutedEventArgs e)
		{
			var btn = sender as Button;
			if (btn != null)
			{
				btn.IsEnabled = false;

				try
				{
					using (var socket = new StreamSocket())
					{
						await socket.ConnectAsync(new HostName(@"127.0.0.1"), @"11111");

						var handler = new WinRtTransferHandler(socket);

						_viewModel.Load(await new LogsClientHandler(2, handler).GetConfigsAsync());

						await handler.CloseAsync();
					}
				}
				catch
				{
				}
				finally
				{
					btn.IsEnabled = true;
				}
			}
		}
開發者ID:ppetrov,項目名稱:iFSA.Service,代碼行數:29,代碼來源:DashboardScreen.xaml.cs

示例10: DoCommand

 private async Task<string> DoCommand(string command)
 {
     StringBuilder strBuilder = new StringBuilder();
     using (StreamSocket clientSocket = new StreamSocket())
     {
         await clientSocket.ConnectAsync(new HostName("192.168.9.108"),  "9001");
         using (DataWriter writer = new DataWriter(clientSocket.OutputStream))
         {
             writer.WriteString(command);
             await writer.StoreAsync();
             writer.DetachStream();
         }
         using (DataReader reader = new DataReader(clientSocket.InputStream))
         {
             reader.InputStreamOptions = InputStreamOptions.Partial;
             await reader.LoadAsync(8192);
             while (reader.UnconsumedBufferLength > 0)
             {
                 strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
                 await reader.LoadAsync(8192);
             }
             reader.DetachStream();
         }
     }
     return (strBuilder.ToString());
 }
開發者ID:mderoode,項目名稱:OVCClient,代碼行數:26,代碼來源:SocketConnection.xaml.cs

示例11: TcpTextWriter

        public TcpTextWriter(string hostName, int port)
        {
            if (hostName == null)
                throw new ArgumentNullException(nameof(hostName));
            if ((port < 0) || (port > ushort.MaxValue))
                throw new ArgumentException("port");

            HostName = hostName;
            Port = port;

#if __IOS__ || MAC
            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
#endif
            try
            {
#if __IOS__ || MAC || ANDROID
                var client = new TcpClient(hostName, port);
                writer = new StreamWriter(client.GetStream());
#elif WINDOWS_PHONE || NETFX_CORE
               
                var socket = new StreamSocket();
                socket.ConnectAsync(new HostName(hostName), port.ToString(CultureInfo.InvariantCulture))
                    .AsTask()
                    .ContinueWith( _ => writer = new StreamWriter(socket.OutputStream.AsStreamForWrite()));
#endif
            }
            catch
            {
#if __IOS__ || MAC
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
#endif
                throw;
            }
        }
開發者ID:roubachof,項目名稱:devices.xunit,代碼行數:34,代碼來源:TcpTextWriter.cs

示例12: ConnectAsync

        internal async Task ConnectAsync(
            HostName hostName,
            string serviceName,
            string user,
            string password)
        {
            if (controlStreamSocket != null)
            {
                throw new InvalidOperationException("Control connection already started.");
            }

            this.hostName = hostName;

            controlStreamSocket = new StreamSocket();
            await controlStreamSocket.ConnectAsync(hostName, serviceName);

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

            writer = new DataWriter(controlStreamSocket.OutputStream);

            readCommands = new List<string>();
            loadCompleteEvent = new AutoResetEvent(false);
            readTask = InfiniteReadAsync();

            FtpResponse response;
            response = await GetResponseAsync();
            VerifyResponse(response, 220);

            response = await UserAsync(user);
            VerifyResponse(response, 331);

            response = await PassAsync(password);
            VerifyResponse(response, 230);
        }
開發者ID:kiewic,項目名稱:FtpClient,代碼行數:35,代碼來源:FtpClient.cs

示例13: ConnectAsync

        public async Task<bool> ConnectAsync(string host, int port, int timeOut = 5000)
        {
            try
            {
                socket = new StreamSocket();
                socket.Control.KeepAlive = true;

                var cts = new CancellationTokenSource();
                cts.CancelAfter(timeOut);

                await socket.ConnectAsync(new HostName(host), port.ToString()).AsTask(cts.Token);

                ReceiveAsync();

                return true;
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                //if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                //    throw;
            }

            Disconnect();

            return false;
        }
開發者ID:KonstantinKolesnik,項目名稱:EcosHub,代碼行數:29,代碼來源:Connection.cs

示例14: IsReachable

    /// <summary>
    /// Checks if remote is reachable. RT apps cannot do loopback so this will alway return false.
    /// You can use it to check remote calls though.
    /// </summary>
    /// <param name="host"></param>
    /// <param name="msTimeout"></param>
    /// <returns></returns>
    public override async Task<bool> IsReachable(string host, int msTimeout = 5000)
    {
      if (string.IsNullOrEmpty(host))
        throw new ArgumentNullException("host");

      if (!IsConnected)
        return false;


     
      try
      {
        var serverHost = new HostName(host);
        using(var client = new StreamSocket())
        {
          await client.ConnectAsync(serverHost, "http");
          return true;
        }


      }
      catch(Exception ex)
      {
        Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
        return false;
      }
    }
開發者ID:Lotpath,項目名稱:Xamarin.Plugins,代碼行數:34,代碼來源:ConnectivityImplementation.cs

示例15: ConnectAsyncInternal

        private async Task ConnectAsyncInternal(HostName hostName)
        {
            _tokenSource = new CancellationTokenSource();

            _socket = new StreamSocket();

            // połącz z kontrolerem na porcie 5555 
            await _socket.ConnectAsync(hostName, "5555", SocketProtectionLevel.PlainSocket);

            // wyslij komendę odblokowującą
            await _socket.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(UnlockCommand).AsBuffer());

            // read the "Accept:EV340\r\n\r\n" response
            //stworzenie bufor na odpowiedź
            IBuffer bufferResponse = new Buffer(128);
            //pobranie do bufora odpowiedzi przychodzącej od kontrolera EV3
            await _socket.InputStream.ReadAsync(bufferResponse, bufferResponse.Capacity, InputStreamOptions.Partial);
            //przekształcenie danych z bufora na ciag znaków w formacie UTF8
            string response = Encoding.UTF8.GetString(bufferResponse.ToArray(), 0, (int)bufferResponse.Length);
            if (string.IsNullOrEmpty(response))
                //zgłoszenie błędu w razie braku odpowiedzi
                throw new Exception("LEGO EV3 brick did not respond to the unlock command.");
            //rozpoczęcie pobierania danych
            await ThreadPool.RunAsync(PollInput);
        }
開發者ID:BananaScheriff,項目名稱:legoev3,代碼行數:25,代碼來源:NetworkCommunication.cs


注:本文中的Windows.Networking.Sockets.StreamSocket.ConnectAsync方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。