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


C# Socket.EndConnect方法代码示例

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


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

示例1: OnConnect

        public void OnConnect( IAsyncResult ar )
        {
            _socket = (Socket) ar.AsyncState;

            try
            {
                _socket.EndConnect(ar);
                if( _socket.Connected )
                {
                    SetupReceiveCallback(_socket);
                    EnableConnect(false);
                }
                else
                {
                    MessageBox.Show("Unable to connect to remote host.");
                    EnableConnect(true);
                    return;
                }
            }
            catch( Exception ex)
            {
                MessageBox.Show(ex.Message, "Connection Error");
                EnableConnect(true);
                return;
            }
        }
开发者ID:shahinpendar,项目名称:ZetaTelnet,代码行数:26,代码来源:MainWindow.cs

示例2: PooledSocket

        public PooledSocket(IPEndPoint endpoint, TimeSpan connectionTimeout, TimeSpan receiveTimeout)
        {
            var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // all operations are "atomic", we do not send small chunks of data
            socket.NoDelay = true;

            var mre = new ManualResetEvent(false);
            var timeout = connectionTimeout == TimeSpan.MaxValue
                            ? Timeout.Infinite
                            : (int)connectionTimeout.TotalMilliseconds;

            socket.ReceiveTimeout = (int)receiveTimeout.TotalMilliseconds;
            socket.SendTimeout = (int)receiveTimeout.TotalMilliseconds;

            socket.BeginConnect(endpoint, iar =>
            {
                try { using (iar.AsyncWaitHandle) socket.EndConnect(iar); }
                catch { }

                mre.Set();
            }, null);

            if (!mre.WaitOne(timeout) || !socket.Connected)
            {
                using (socket)
                    throw new TimeoutException("Could not connect to " + endpoint);
            }

            this.socket = socket;
            this.endpoint = endpoint;

            this.inputStream = new BufferedStream(new BasicNetworkStream(socket));
        }
开发者ID:Darkseal,项目名称:EnyimMemcached,代码行数:34,代码来源:PooledSocket.cs

示例3: PooledSocket

        public PooledSocket(SocketPool socketPool, IPEndPoint endPoint, int sendReceiveTimeout, int connectTimeout)
        {
            this.socketPool = socketPool;
            Created = DateTime.Now;

            //Set up the socket.
            socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, sendReceiveTimeout);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, sendReceiveTimeout);
            socket.ReceiveTimeout = sendReceiveTimeout;
            socket.SendTimeout = sendReceiveTimeout;

            //Do not use Nagle's Algorithm
            socket.NoDelay = true;

            //Establish connection asynchronously to enable connect timeout.
            IAsyncResult result = socket.BeginConnect(endPoint, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(connectTimeout, false);
            if (!success) {
                try { socket.Close(); } catch { }
                throw new SocketException();
            }
            socket.EndConnect(result);

            //Wraps two layers of streams around the socket for communication.
            stream = new BufferedStream(new NetworkStream(socket, false));
        }
开发者ID:XiaoPingJiang,项目名称:cyqdata,代码行数:27,代码来源:PooledSocket.cs

示例4: NetworkConnection

        /// <summary>
        /// Initializes a new instance of the <see cref="ProScanMobile.NetworkConnection"/> class.
        /// </summary>
        /// <description>
        /// Creates a new _tcpSocket and tries to connect to Host/Port 
        /// </description>
        /// <param name="host">Host</param>
        /// <param name="port">Port</param>
        public NetworkConnection(string host, int port)
        {
            _connectDone.Reset ();

            try
            {
                IPHostEntry ipHostInfo = Dns.GetHostEntry (host);
                IPAddress ipAddress = ipHostInfo.AddressList [0];
                IPEndPoint remoteEP = new IPEndPoint (ipAddress, port);

                _tcpSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _tcpSocket.Blocking = true;

                var result = _tcpSocket.BeginConnect (remoteEP, null, null);

                bool success = result.AsyncWaitHandle.WaitOne (5000, true);
                if (success) {
                    _tcpSocket.EndConnect (result);
                    _connectionStatus = ConnectionStatus.Connected;
                    _connectionStatusMessage = "Connected.";
                } else {
                    _tcpSocket.Close ();
                    _connectionStatus = ConnectionStatus.Error;
                    _connectionStatusMessage = "Connection timed out.";
                }
            } catch {
                _connectionStatus = ConnectionStatus.Error;
                _connectionStatusMessage = string.Format("An error occured connecting to {0} on port {1}.", host, port);
                _connectDone.Set();
                return;
            } finally {
                _connectDone.Set ();
            }
        }
开发者ID:jeanfrancoisdrapeau,项目名称:ProScanAlert,代码行数:42,代码来源:NetworkConnection.cs

示例5: OpenConnection

        protected Connection OpenConnection(IPEndPoint endpoint, Action<Connection> connectionInitializer)
        {
            Socket tmp = null;
            try
            {
                tmp = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                var asyncState = tmp.BeginConnect(endpoint, null, null);
                if (asyncState.AsyncWaitHandle.WaitOne(ConnectTimeout, true))
                {
                    tmp.EndConnect(asyncState); // checks for exception
                    var conn = ProtocolFactory.CreateConnection(endpoint) ?? new Connection();
                    
                    if (connectionInitializer != null) connectionInitializer(conn);

                    conn.Socket = tmp;
                    var processor = ProtocolFactory.GetProcessor();
                    conn.SetProtocol(processor);
                    processor.InitializeOutbound(Context, conn); 
                    StartReading(conn);
                    conn.InitializeClientHandshake(Context);
                    tmp = null;
                    return conn;
                }
                else
                {
                    Close();
                    throw new TimeoutException("Unable to connect to endpoint");
                }
            }
            finally
            {
                if (tmp != null) ((IDisposable)tmp).Dispose();
            }
        }
开发者ID:ReinhardHsu,项目名称:NetGain,代码行数:34,代码来源:TcpHandler.cs

示例6: AddSocket

 public void AddSocket(EndPoint endPoint, Action<Netronics, IChannel> action = null)
 {
     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     socket.BeginConnect(endPoint, ar =>
         {
             socket.EndConnect(ar);
             var channel = AddChannel(Properties.GetChannelPipe().CreateChannel(this, socket));
             if (action != null)
                 action(this, channel);
             channel.Connect();
         }, null);
 }
开发者ID:shlee322,项目名称:Netronics,代码行数:12,代码来源:Netronics.cs

示例7: AsyncConnect

		private static void AsyncConnect(Socket socket, Func<Socket, AsyncCallback, object, IAsyncResult> connect, TimeSpan timeout) {
			var asyncResult = connect(socket, null, null);
			if (asyncResult.AsyncWaitHandle.WaitOne(timeout)) {
				return;
			}

			try {
				socket.EndConnect(asyncResult);
			} catch (SocketException) {

			} catch (ObjectDisposedException) {

			}
		}
开发者ID:GodLesZ,项目名称:svn-dump,代码行数:14,代码来源:SocketExtensions.cs

示例8: Open

 public static ISocket Open(IPEndPoint endPoint, int connectTimeout = Timeout.Infinite, int receiveTimeout = Timeout.Infinite, int sendTimeout = Timeout.Infinite) {
     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true, SendTimeout = sendTimeout, ReceiveTimeout = receiveTimeout };
     var ar = socket.BeginConnect(endPoint, null, null);
     if(ar.AsyncWaitHandle.WaitOne(connectTimeout)) {
         socket.EndConnect(ar);
     } else {
         try {
             socket.Shutdown(SocketShutdown.Both);
             socket.Close();
             socket.Dispose();
         } catch { }
         throw new SocketException(10060);
     }
     return new SocketAdapter(socket);
 }
开发者ID:MindTouch,项目名称:MindTouch.Clacks,代码行数:15,代码来源:SocketAdapter.cs

示例9: Connected

 void Connected(IAsyncResult iar)
 {
     client = (Socket)iar.AsyncState;
     try
     {
         client.EndConnect(iar);
         this.Invoke(new MethodInvoker( delegate() {
             Text = "DreamViever Connected:" + client.RemoteEndPoint.ToString(); }));
         client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
     }
     catch (SocketException)
     {
         MessageBox.Show("Error connecting to DvbDream");
     }
 }
开发者ID:buidan,项目名称:dreamviewer,代码行数:15,代码来源:ViewVideo.cs

示例10: ConnectCallback

        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                client = (Socket)ar.AsyncState;
                client.EndConnect(ar);

                Send(username + "\0|Login"); // Login on connect

                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receive, null);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Error " + ex.Message, "Error!");
            }
        }
开发者ID:Hamarz,项目名称:CodeWithMe,代码行数:16,代码来源:Client.cs

示例11: ConnectWithTimeout

        private static void ConnectWithTimeout(Socket socket, IPEndPoint endpoint, int timeout)
        {
            var mre = new ManualResetEvent(false);

            socket.BeginConnect(endpoint, iar =>
            {
                try { using (iar.AsyncWaitHandle) socket.EndConnect(iar); }
                catch { }

                mre.Set();
            }, null);

            if (!mre.WaitOne(timeout) || !socket.Connected)
                using (socket)
                    throw new TimeoutException("Could not connect to " + endpoint);
        }
开发者ID:ZhaoYngTest01,项目名称:EnyimMemcached,代码行数:16,代码来源:PooledSocket.cs

示例12: Connection

        /// <summary>
        /// Create socket with connection timeout.
        /// </summary>
        public Connection(IPEndPoint address, int timeoutMillis, int maxSocketIdleMillis)
        {
            this.maxSocketIdleMillis = (double)(maxSocketIdleMillis);

            try
            {
                socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                socket.NoDelay = true;

                if (timeoutMillis > 0)
                {
                    socket.SendTimeout = timeoutMillis;
                    socket.ReceiveTimeout = timeoutMillis;
                }
                else
                {
                    // Do not wait indefinitely on connection if no timeout is specified.
                    // Retry functionality will attempt to reconnect later.
                    timeoutMillis = 2000;
                }

                IAsyncResult result = socket.BeginConnect(address, null, null);
                WaitHandle wait = result.AsyncWaitHandle;

                // Never allow timeoutMillis of zero because WaitOne returns
                // immediately when that happens!
                if (wait.WaitOne(timeoutMillis))
                {
                    // EndConnect will automatically close AsyncWaitHandle.
                    socket.EndConnect(result);
                }
                else
                {
                    // Close socket, but do not close AsyncWaitHandle. If AsyncWaitHandle is closed,
                    // the disposed handle can be referenced after the timeout exception is thrown.
                    // The handle will eventually get closed by the garbage collector.
                    // See: https://social.msdn.microsoft.com/Forums/en-US/313cf28c-2a6d-498e-8188-7a0639dbd552/tcpclientbeginconnect-issue?forum=netfxnetcom
                    socket.Close();
                    throw new SocketException((int)SocketError.TimedOut);
                }
                timestamp = DateTime.UtcNow;
            }
            catch (Exception e)
            {
                throw new AerospikeException.Connection(e);
            }
        }
开发者ID:vonbv,项目名称:aerospike-client-csharp,代码行数:50,代码来源:Connection.cs

示例13: Connect

        public static NetworkConnection Connect(IPEndPoint endPoint, TimeSpan timeout = default(TimeSpan))
        {
            Util.Log("Connecting to terminal...", endPoint.Address);

            // default timeout is five seconds
            if (timeout <= TimeSpan.Zero)
                timeout = TimeSpan.FromSeconds(5);

            // Enter the gate.  This will block until it is safe to connect.
            GateKeeper.Enter(endPoint, timeout);

            
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                // Now we can try to connect, using the specified timeout.
                var result = socket.BeginConnect(endPoint, ar =>
                    {
                        try
                        {
                            socket.EndConnect(ar);
                        }
                        catch
                        {
                            // Swallow any exceptions.  The socket is probably closed.
                        }
                    }, null);
                result.AsyncWaitHandle.WaitOne(timeout, true);
                if (!socket.Connected)
                {
                    socket.Close();
                    GateKeeper.Exit(endPoint);
                    throw new TimeoutException("Timeout occurred while trying to connect to the terminal.");
                }
            }
            catch
            {
                // just in case
                GateKeeper.Exit(endPoint);
                throw;
            }

            Util.Log("Connected!", endPoint.Address);

            return new NetworkConnection(socket, true);
        }
开发者ID:synel,项目名称:syndll2,代码行数:46,代码来源:NetworkConnection.cs

示例14: BeginConnect

        /// <summary>
        /// begin connect
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="host"></param>
        /// <param name="callback"></param>
        /// <exception cref="ArgumentNullException">endPoint is null</exception>
        /// <exception cref="ArgumentNullException">host is null</exception>
        /// <exception cref="ArgumentNullException">callback is null</exception>
        public static void BeginConnect(EndPoint endPoint, IHost host, Action<IConnection> callback)
        {
            if (endPoint == null) throw new ArgumentNullException("endPoint");
            if (host == null) throw new ArgumentNullException("host");
            if (callback == null) throw new ArgumentNullException("callback");

            Log.Trace.Debug(string.Concat("begin connect to ", endPoint.ToString()));

            var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.BeginConnect(endPoint, ar =>
                {
                    try
                    {
                        socket.EndConnect(ar);
                        socket.NoDelay = true;
                        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                        socket.ReceiveBufferSize = host.SocketBufferSize;
                        socket.SendBufferSize = host.SocketBufferSize;
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            socket.Close();
                            socket.Dispose();
                        }
                        catch { }

                        Log.Trace.Error(ex.Message, ex);
                        callback(null); return;
                    }

                    callback(new DefaultConnection(host.NextConnectionID(), socket, host));
                }, null);
            }
            catch (Exception ex)
            {
                Log.Trace.Error(ex.Message, ex);
                callback(null);
            }
        }
开发者ID:zhujunxxxxx,项目名称:FastNetwork,代码行数:52,代码来源:SocketConnector.cs

示例15: Connect

        /// <summary>
        /// Disconnects (if needed) and connects the specified end point.
        /// </summary>
        /// <param name="endPoint">The end point.</param>
        public void Connect( IPEndPoint endPoint )
        {
            Disconnect();

            sock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
            var asyncResult = sock.BeginConnect( endPoint, null, null );

            IsConnected = asyncResult.AsyncWaitHandle.WaitOne( ConnectionTimeout );

            if ( !IsConnected )
            {
                sock.Close();
                return;
            }

            sock.EndConnect( asyncResult );

            sockStream = new NetworkStream( sock, true );

            Reader = new BinaryReader( sockStream );
            Writer = new BinaryWriter( sockStream );
        }
开发者ID:Redflameman0,项目名称:SteamKit2,代码行数:26,代码来源:TcpSocket.cs


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