当前位置: 首页>>代码示例>>C#>>正文


C# Socket.ConnectAsync方法代码示例

本文整理汇总了C#中System.Net.Sockets.Socket.ConnectAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.ConnectAsync方法的具体用法?C# Socket.ConnectAsync怎么用?C# Socket.ConnectAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.Socket的用法示例。


在下文中一共展示了Socket.ConnectAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: IsPortReachable

        public async Task<bool> IsPortReachable(string host, int port = 80, int msTimeout = 5000)
        {
            if (string.IsNullOrEmpty(host))
                throw new ArgumentNullException("host");

            return await Task.Run(() =>
                {
                    var clientDone = new ManualResetEvent(false);
                    var reachable = false;
                    var hostEntry = new DnsEndPoint(host, port);
                    using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                    {
                        var socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry };
                        socketEventArg.Completed += (s, e) =>
                        {
                            reachable = e.SocketError == SocketError.Success;

                            clientDone.Set();
                        };

                        clientDone.Reset();

                        socket.ConnectAsync(socketEventArg);

                        clientDone.WaitOne(msTimeout);

                        return reachable;
                    }
                });
        }
开发者ID:vinzandtonz,项目名称:Cheesebaron.MvxPlugins,代码行数:30,代码来源:Connectivity.cs

示例2: InitConnect

        internal void InitConnect(IPEndPoint serverEndPoint,
                                  Action<IPEndPoint, Socket> onConnectionEstablished,
                                  Action<IPEndPoint, SocketError> onConnectionFailed,
                                  ITcpConnection connection,
                                  TimeSpan connectionTimeout)
        {
            if (serverEndPoint == null)
                throw new ArgumentNullException("serverEndPoint");
            if (onConnectionEstablished == null)
                throw new ArgumentNullException("onConnectionEstablished");
            if (onConnectionFailed == null)
                throw new ArgumentNullException("onConnectionFailed");

            var socketArgs = _connectSocketArgsPool.Get();
            var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socketArgs.RemoteEndPoint = serverEndPoint;
            socketArgs.AcceptSocket = connectingSocket;
            var callbacks = (CallbacksStateToken) socketArgs.UserToken;
            callbacks.OnConnectionEstablished = onConnectionEstablished;
            callbacks.OnConnectionFailed = onConnectionFailed;
            callbacks.PendingConnection = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout));

            AddToConnecting(callbacks.PendingConnection);

            try
            {
                var firedAsync = connectingSocket.ConnectAsync(socketArgs);
                if (!firedAsync)
                    ProcessConnect(socketArgs);
            }
            catch (ObjectDisposedException)
            {
                HandleBadConnect(socketArgs);
            }
        }
开发者ID:jen20,项目名称:tcp-servers-talk,代码行数:35,代码来源:TcpClientConnector.cs

示例3: Wp7ConnectionDriver

        public Wp7ConnectionDriver(Runtime.Runtime runtime, MemoryStream memStream)
            : base(false)
        {
            try
            {
                _memStream = memStream;
                _runtime = runtime;

                _runtime.Driver = this;

                _incoming = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnected);
                args.RemoteEndPoint = new DnsEndPoint(HOST, PORT);

                if (!_incoming.ConnectAsync(args))
                {
                    OnConnected(null, args);
                }
            }
            catch (SocketException e)
            {
                throw new ConnectionException(e);
            }
        }
开发者ID:visual14ph,项目名称:f1livetiming,代码行数:26,代码来源:Wp7ConnectionDriver.cs

示例4: SendData

        public void SendData(string data)
        {
            if (String.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentNullException("data");
            }

            dataIn = data;

            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

            DnsEndPoint hostEntry = new DnsEndPoint(_serverName, _port);

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed);
            socketEventArg.RemoteEndPoint = hostEntry;

            socketEventArg.UserToken = sock;

            try
            {
                sock.ConnectAsync(socketEventArg);
            }
            catch (SocketException ex)
            {
                throw new SocketException((int)ex.ErrorCode);
            }
        }
开发者ID:shivanshuag,项目名称:hit-me-phone,代码行数:28,代码来源:AsynchronousSocketClient.cs

示例5: ConnectAsync

        public static void ConnectAsync(this EndPoint remoteEndPoint, EndPoint localEndPoint, ConnectedCallback callback, object state)
        {
            var e = CreateSocketAsyncEventArgs(remoteEndPoint, callback, state);
            
#if NETSTANDARD

            if (localEndPoint != null)
            {
                var socket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                socket.ExclusiveAddressUse = false;
                socket.Bind(localEndPoint);
                socket.ConnectAsync(e);
            }
            else
            {
                Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, e);
            }            
#else
            var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            
            if (localEndPoint != null)
            {
                socket.ExclusiveAddressUse = false;
                socket.Bind(localEndPoint);
            }
                
            socket.ConnectAsync(e);
#endif
        }
开发者ID:ChuckFork,项目名称:SuperSocket.ClientEngine,代码行数:29,代码来源:ConnectAsyncExtension.Net45.cs

示例6: ConnectAsyncInternal

        private static void ConnectAsyncInternal(this EndPoint remoteEndPoint, EndPoint localEndPoint, ConnectedCallback callback, object state)
        {
            if (remoteEndPoint is DnsEndPoint)
            {
                var dnsEndPoint = (DnsEndPoint)remoteEndPoint;

                var asyncResult = Dns.BeginGetHostAddresses(dnsEndPoint.Host, OnGetHostAddresses,
                    new DnsConnectState
                    {
                        Port = dnsEndPoint.Port,
                        Callback = callback,
                        State = state,
                        LocalEndPoint = localEndPoint
                    });

                if (asyncResult.CompletedSynchronously)
                    OnGetHostAddresses(asyncResult);
            }
            else
            {
                var e = CreateSocketAsyncEventArgs(remoteEndPoint, callback, state);
                var socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                if (localEndPoint != null)
                {
                    socket.ExclusiveAddressUse = false;
                    socket.Bind(localEndPoint);
                }

                socket.ConnectAsync(e);
            }
        }
开发者ID:ChuckFork,项目名称:SuperSocket.ClientEngine,代码行数:32,代码来源:ConnectAsyncExtension.Net.cs

示例7: SendCommand

 private void SendCommand(string command)
 {
     var data = GetCommandBytes(command);
     // Would love to use TcpClient here...
     using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         var serverAddr = IPAddress.Parse(this.host);
         var endPoint = new IPEndPoint(serverAddr, this.port);
         var args = new SocketAsyncEventArgs { RemoteEndPoint = endPoint };
         args.SetBuffer(data, 0, data.Length);
         using (var done = new ManualResetEvent(false))
         {
             // When there's a buffer present, ConnectAsync sends the data as well
             args.Completed += (sender, e) => done.Set();
             if (!socket.ConnectAsync(args))
             {
                 throw new Exception("Failed to send command to amplifier");
             }
             if (!done.WaitOne(TimeSpan.FromSeconds(5)))
             {
                 throw new Exception("Timed out send command to amplifier");
             }
         }
     }
 }
开发者ID:ivandrofly,项目名称:DemoCode,代码行数:25,代码来源:OnkyoController.cs

示例8: Connect

        public string Connect(string hostName, int portNumber)
        {
            string result = string.Empty;
            DnsEndPoint hostEntry = new DnsEndPoint (hostName, portNumber);
            _socket = new Socket (
                AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp
            );
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs ();
            socketEventArg.RemoteEndPoint = hostEntry;

            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs> (delegate(object s, SocketAsyncEventArgs e)
                {
                    result = e.SocketError.ToString ();
                    _clientDone.Set ();
                }
            );

            _clientDone.Reset ();
            _socket.ConnectAsync (socketEventArg);
            _clientDone.WaitOne (TIMEOUT_MILLISECONDS);

            return result;
        }
开发者ID:meatballhat,项目名称:box-o-sand,代码行数:25,代码来源:SocketClient.cs

示例9: Open

        public async Task<bool> Open(string address = null, int port = -1)
        {
            try
            {
                IPEndPoint server = new IPEndPoint(IPAddress.Parse(_address), _port);
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
				args.SocketFlags = SocketFlags.None;
                args.RemoteEndPoint = server;
                var awaitable = new SocketAwaitable(args);
                awaitable.OnCompleted(() => {
                    RaiseConnected();
                    //Flush();                    
                    //Receive();
                });

                _socket = new Socket(server.AddressFamily, SocketType.Stream, ProtocolType.Tcp);                
                await _socket.ConnectAsync(awaitable);
                return awaitable.IsCompleted;
            }
            catch (Exception ex)
            {
                RaiseError(ex);
                throw;
            }
        }
开发者ID:jcapuano328,项目名称:dotnet-sockets,代码行数:25,代码来源:AsyncSocketClient.awaitable.cs

示例10: ConnectAsync

 public bool ConnectAsync(SocketAsyncEventArgs connectArgs, out Socket socket)
 {
     socket = Acquire();
     if (socket.Connected)
         return false;
     return socket.ConnectAsync(connectArgs);
 }
开发者ID:DTBruce,项目名称:csredis,代码行数:7,代码来源:SocketPool.cs

示例11: ConnectTo

		public void ConnectTo(string ip, int port)
		{

			State = ConnectionState.NotConnected;

			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

			IPAddress[] ips = Dns.GetHostAddresses(ip);
			var addr = ips[0];
			var hostEndPoint = new IPEndPoint(addr, port);

			var connectEA = new SocketAsyncEventArgs();

			connectEA.RemoteEndPoint = hostEndPoint;
			connectEA.Completed += (object sender, SocketAsyncEventArgs e)=>{

				switch (e.LastOperation)
				{
				case SocketAsyncOperation.Connect:
					UnityEngine.Debug.Log("Connect success");
					break;
				default:
					throw new ArgumentException("The last operation completed on the socket was not a receive or send");
				}

				connectEA.Dispose();

				State = ConnectionState.Connected;

			};

			State = ConnectionState.Connecting;

			socket.ConnectAsync(connectEA);
		}
开发者ID:xclouder,项目名称:godbattle,代码行数:35,代码来源:NetworkInterface.cs

示例12: Connect

        private static Task<Socket> Connect(IPAddress address, int port)
        {
            var ipe = new IPEndPoint(address, port);
            var socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            var tcs = new TaskCompletionSource<Socket>();

            var sea = new SocketAsyncEventArgs();
            sea.RemoteEndPoint = ipe;
            sea.Completed += (sender, e) =>
            {
                if (e.SocketError != SocketError.Success)
                {
                    tcs.TrySetException(e.ConnectByNameError);
                }
                else
                {
                    tcs.TrySetResult(socket);
                }
            };

            socket.ConnectAsync(sea);

            return tcs.Task;
        }
开发者ID:jango2015,项目名称:OwinHttpClient,代码行数:25,代码来源:NetworkStreamFactory.cs

示例13: ConnectAsync

        public override bool ConnectAsync(TimeSpan timeout, TransportAsyncCallbackArgs callbackArgs)
        {
            // TODO: set socket connect timeout to timeout
            this.callbackArgs = callbackArgs;
            DnsEndPoint dnsEndPoint = new DnsEndPoint(this.transportSettings.Host, this.transportSettings.Port);

            SocketAsyncEventArgs connectEventArgs = new SocketAsyncEventArgs();
            connectEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnectComplete);
            connectEventArgs.RemoteEndPoint = dnsEndPoint;
            connectEventArgs.UserToken = this;

#if MONOANDROID
            // Work around for Mono issue: https://github.com/rabbitmq/rabbitmq-dotnet-client/issues/171
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            bool connectResult = socket.ConnectAsync(connectEventArgs);
#else
            // On Linux platform, socket connections are allowed to be initiated on the socket instance 
            // with hostname due to multiple IP address DNS resolution possibility.
            // They suggest either using static Connect API or IP address directly.
            bool connectResult = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, connectEventArgs);
#endif
            if (connectResult)
            {
                return true;
            }
            else
            {
                this.Complete(connectEventArgs, true);
                return false;
            }
        }
开发者ID:Azure,项目名称:azure-amqp,代码行数:31,代码来源:TcpTransportInitiator.cs

示例14: OnSend

        void OnSend(object sender, EventArgs args)
        {
            //定义一个字节数组,并将文本框的的类容转换为字节数组后存入
            byte[] bytes = Encoding.UTF8.GetBytes(txtToSend.Text);

            //显示信息,可不要。
            txtToSend.Text += "/r/nDnsSafeHost:" + Application.Current.Host.Source.DnsSafeHost;

            //将同步上下文设置在当前上下文(线程,主线程,可控制UI的)
            syn = SynchronizationContext.Current;

            //为socket创建示例,并设置相关属性。
            socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //定义并实例一个Socket参数
            SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs();

            //设置到远程终节点属性(4502端口,为什么是4502,MS的SL通信安全上有)
            // socketArgs.RemoteEndPoint = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, 4502);
            socketArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("10.32.1.219"), 4502);
            //new IPEndPoint(IPAddress.Parse(ipadd)
            //设置好当Socket任何一个动作完成时的回调函数。
            socketArgs.Completed += new EventHandler<SocketAsyncEventArgs>(socketArgs_Completed);
            //Socket参数的用户标识,实际上就是一个可以传递的OBJECT参数。
            socketArgs.UserToken = bytes;
            //执行连接。
            socket.ConnectAsync(socketArgs);
        }
开发者ID:powernick,项目名称:CodeLib,代码行数:28,代码来源:MainPage.xaml.cs

示例15: ConnectTo

        public void ConnectTo(DnsEndPoint hostEntry)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketError _lastError = SocketError.NotConnected;
            SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();

            socketEventArgs.RemoteEndPoint = hostEntry;
            socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                _lastError = e.SocketError;
                _End();
                // Install read and write handler
                _socketReadEventArgs = new SocketAsyncEventArgs();
                _socketReadEventArgs.RemoteEndPoint = _socket.RemoteEndPoint;
                _socketReadEventArgs.SetBuffer(new byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
                _socketReadEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_AsyncCallComplete);

                _socketWriteEventArgs = new SocketAsyncEventArgs();
                _socketWriteEventArgs.RemoteEndPoint = _socket.RemoteEndPoint;
                _socketWriteEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_AsyncCallComplete);
            });

            // async connect
            _Reset();
            _socket.ConnectAsync(socketEventArgs);
            _BlockUI();

            if (_lastError != SocketError.Success)
            {
                // connection failed
                throw new Exception(String.Format(LocalizedStrings.Get("Net_StreamSocket_ConnectFailed"), hostEntry, _lastError.ToString()));
            }            
        }
开发者ID:ErikPel,项目名称:windows-phone,代码行数:33,代码来源:StreamSocket.cs


注:本文中的System.Net.Sockets.Socket.ConnectAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。