当前位置: 首页>>代码示例>>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;未经允许,请勿转载。