System.Net.Sockets.Socket.BeginConnect C# (CSharp) Method

BeginConnect() public method

public BeginConnect ( IPAddress address, int port, AsyncCallback requestCallback, object state ) : IAsyncResult
address System.Net.IPAddress
port int
requestCallback AsyncCallback
state object
return IAsyncResult
        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
            if (CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }
            if (!TcpValidationHelpers.ValidatePortNumber(port))
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }
            if (!CanTryAddressFamily(address.AddressFamily))
            {
                throw new NotSupportedException(SR.net_invalidversion);
            }

            IAsyncResult result = BeginConnect(new IPEndPoint(address, port), requestCallback, state);
            if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
            return result;
        }

Same methods

Socket::BeginConnect ( EndPoint remoteEP, AsyncCallback callback, object state ) : IAsyncResult
Socket::BeginConnect ( string host, int port, AsyncCallback requestCallback, object state ) : IAsyncResult

Usage Example

        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
            var ControllerPort = 40001;
            var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            var header = "@";
            var command = "00C";
            var checksum = "E3";
            var end = "\r\n";
            var data = header + command + checksum + end;
            byte[] bytes = new byte[1024];

            //Start Connect
            _connectDone.Reset();
            watch.Start();
            _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
            //wait 2s
            _connectDone.WaitOne(2000, false);

            var text = (_client.Connected) ? "ok" : "ng";
            richTextBox1.AppendText(text + "\r\n");
            watch.Stop();
            richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
        }
All Usage Examples Of System.Net.Sockets.Socket::BeginConnect