ConnectAsync() public method

public ConnectAsync ( SocketAsyncEventArgs e ) : bool
e SocketAsyncEventArgs
return bool
        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;
                    }
                });
        }
Exemplo n.º 2
1
        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);
            }
        }
Exemplo n.º 3
0
 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");
             }
         }
     }
 }
        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;
        }
        public async System.Threading.Tasks.ValueTask <ConnectionContext> ConnectAsync(EndPoint endpoint, System.Threading.CancellationToken cancellationToken)
        {
            var socket = new System.Net.Sockets.Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                LingerState = new LingerOption(true, 0),
                NoDelay     = true
            };

            socket.EnableFastPath();
            var completion = new SingleUseSocketAsyncEventArgs
            {
                RemoteEndPoint = endpoint
            };

            if (!socket.ConnectAsync(completion))
            {
                completion.Complete();
            }

            await completion;

            if (completion.SocketError != SocketError.Success)
            {
                throw new SocketConnectionException($"Unable to connect to {endpoint}. Error: {completion.SocketError}");
            }

            var scheduler  = this.schedulers.GetScheduler();
            var connection = new SocketConnection(socket, this.memoryPool, scheduler, this.trace);

            connection.Start();
            return(connection);
        }
        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
        }
        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);
            }
        }
        public TcpIPClient(string ip, int port)
        {
            LogDir = "logs";
            if (!IsValidIP(ip))
            {
                Log($"TcpIPClient 생성중 잘못된 ip가 입력됨: {ip}");
                throw new ArgumentException("Wrong IP address.");
            }

            if (!IsValidPort(port))
            {
                Log($"TcpIPClient 생성중 잘못된 port가 입력됨: {port}");
                throw new ArgumentException("Wrong port.");
            }
            try
            {
                Log("TcpIPClient 초기화 중...");
                this.ip = ip;
                this.port = port;
                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port);
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = ipep;
                args.Completed -= new EventHandler<SocketAsyncEventArgs>(ConnectCompleted);
                args.Completed += new EventHandler<SocketAsyncEventArgs>(ConnectCompleted);
                client.ConnectAsync(args);

                closed = false;
            }
            catch (Exception e)
            {
                Log($"TcpIPClient 초기화 중 에러 발생!\n{e.ToString()}");
            }
        }
Exemplo n.º 9
0
 public bool ConnectAsync(SocketAsyncEventArgs connectArgs, out Socket socket)
 {
     socket = Acquire();
     if (socket.Connected)
         return false;
     return socket.ConnectAsync(connectArgs);
 }
Exemplo n.º 10
0
        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;
            }
        }
        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;
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Begin the connection with host.
        /// </summary>
        internal void BeginConnect()
        {
            if (!Disposed)
            {
                //----- Create Socket!
                FSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                FSocket.Bind(InternalLocalEndPoint);
                FSocket.ReceiveBufferSize = Host.SocketBufferSize;
                FSocket.SendBufferSize    = Host.SocketBufferSize;

                FReconnectTimer.Change(Timeout.Infinite, Timeout.Infinite);

                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                e.Completed += new EventHandler <SocketAsyncEventArgs>(BeginConnectCallbackAsync);
                e.UserToken  = this;

                if (FProxyInfo == null)
                {
                    e.RemoteEndPoint = FRemoteEndPoint;
                }
                else
                {
                    FProxyInfo.Completed   = false;
                    FProxyInfo.SOCKS5Phase = SOCKS5Phase.spIdle;

                    e.RemoteEndPoint = FProxyInfo.ProxyEndPoint;
                }

                if (!FSocket.ConnectAsync(e))
                {
                    BeginConnectCallbackAsync(this, e);
                }
            }
        }
        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);
            }
        }
Exemplo n.º 14
0
        public IvySocket(string hostAddress, int hostPort)
        {
            ipAddress = hostAddress;
            port = hostPort;

            SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs();
            IPAddress ip = IPAddress.Parse(ipAddress);

            /* Creation de la socket */

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

            /* Connexion de la socket */

            socketArgs.RemoteEndPoint = new IPEndPoint(ip, port);
            socketArgs.Completed += new EventHandler<SocketAsyncEventArgs>(socketConnected);

            sock.ConnectAsync(socketArgs);

            /* Args pour l'envoi et la reception de donnees */

            /*sendArgs = new SocketAsyncEventArgs();
            sendArgs.Completed += new EventHandler<SocketAsyncEventArgs>(sendCompleted);

            recvArgs = new SocketAsyncEventArgs();
            recvArgs.Completed += new EventHandler<SocketAsyncEventArgs>(receiveCompleted);*/
        }
Exemplo n.º 15
0
        internal string Connect()     //returns error
        {
            SocketAsyncEventArgs args = new SocketAsyncEventArgs();

            args.SocketClientAccessPolicyProtocol = SocketClientAccessPolicyProtocol.Tcp;
            args.UserToken      = socket;
            args.RemoteEndPoint = endPoint;

            args.Completed += OnConnect;


            autoEvent.Reset();
            socket.ConnectAsync(args);
            autoEvent.WaitOne();

            if (args.SocketError == SocketError.Success)
            {
                return("");
            }
            else
            {
                Exception p = args.ConnectByNameError;
                return(p.Message);
            }
        }
Exemplo n.º 16
0
        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;
        }
        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);
            }
        }
Exemplo n.º 18
0
        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);
        }
Exemplo n.º 19
0
		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);
		}
Exemplo n.º 20
0
        /// <summary>
        /// Connects the specified socket.
        /// </summary>
        /// <param name="socket">The socket.</param>
        /// <param name="endpoint">The IP endpoint.</param>
        /// <param name="timeout">The timeout in milliseconds.</param>
        public static async Task ConnectAsync(this System.Net.Sockets.Socket socket, EndPoint endpoint, int timeout)
        {
            TimeSpan timeOut = TimeSpan.FromMilliseconds(timeout);

            var cancellationCompletionSource = new TaskCompletionSource <bool>();

            try
            {
                using (var cts = new CancellationTokenSource(timeOut))
                {
                    var task = socket.ConnectAsync(endpoint);

                    using (cts.Token.Register(() => cancellationCompletionSource.TrySetResult(true)))
                    {
                        if (task != await Task.WhenAny(task, cancellationCompletionSource.Task))
                        {
                            throw new OperationCanceledException(cts.Token);
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                socket.Close();
                throw new SocketException(ConnectionTimedOutStatusCode);
            }
        }
Exemplo n.º 21
0
        public bool ConnectAsync(EndPoint EPhost)
        {
            UserInitiatedDisconnect = false;
            //Creates the Socket for sending data over TCP.
            Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Connects to the host using IPEndPoint.
            try
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = EPhost;
                args.Completed     += new EventHandler <SocketAsyncEventArgs>(OnClientConnected);
                Client.ConnectAsync(args);
            }
            catch (SocketException e2)
            {
                if (m_Logger != null)
                {
                    m_Logger.LogError(ToString(), MessageImportance.Highest, e2.ToString());
                }
                return(false);
            }

            return(true);
        }
Exemplo n.º 22
0
		public bool Connect(VirtualServer SVR)
		{
			try
			{

                Clear();

                CancelSocket = false;

				ClientSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
				iConnect = new System.Net.Sockets.SocketAsyncEventArgs();

                iConnect.Completed += new EventHandler<SocketAsyncEventArgs>(iConnect_Completed);
                iConnect.RemoteEndPoint = new DnsEndPoint(SVR.Host, SVR.Port); //.SocketClientAccessPolicyProtocol = TCP

				if (!ClientSocket.ConnectAsync(iConnect))
				{
					iConnect_Completed(null, iConnect); // Synchronously
				}

                return true;

			}
            catch (Exception ex) { Close(952, "Socket_Connect: " + ex.Message); return false; }
		}
Exemplo n.º 23
0
        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()));
            }            
        }
Exemplo n.º 24
0
        public void Connect(string connectionStr)
        {
            string[] splitStr = connectionStr.Split(':');
            if (splitStr.Length != 2)
            {
                throw new ArgumentException();
            }

            IPAddress ipAddress = IPAddress.Parse(splitStr[0]);
            if (null == ipAddress)
            {
                throw new ArgumentException();
            }

            int port = 0;
            if (!int.TryParse(splitStr[1], out port))
            {
                throw new ArgumentException();
            }

            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

            Socket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
            SocketAsyncEventArgs e = new SocketAsyncEventArgs();
            e.Completed += ConnectCallback;
            if (!Socket.ConnectAsync(e))
            {
                ConnectCallback(Socket, e);
            }
        }
Exemplo n.º 25
0
    public async Task TryConnectAsync(string ip, int port, CancellationToken token)
    {
        if (IsConnected)
        {
            throw new InvalidOperationException("Клиент уже подключен");
        }

        if (!IPAddress.TryParse(ip, out var ipAddress))
        {
            throw new InvalidOperationException("Не валидный IP адрес");
        }

        _clientSocket = new System.Net.Sockets.Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        while (!_clientSocket.Connected)
        {
            await Task.Delay(TimeSpan.FromSeconds(1), token);

            try
            {
                await _clientSocket.ConnectAsync(ipAddress, port, token);

                this.Events.CallClientConnectedEvent(this, ipAddress);
            }
            catch
            {
            }
        }

        var _ = Task.Run(() => DataReceiverAsync(socketClient, _token), linkedCts.Token);


        Log.Logger.Information("Подключились к серверу");
    }
Exemplo n.º 26
0
        public async Task ConnectAsync(IPEndPoint endpoint)
        {
            socket = new System.Net.Sockets.Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            await socket.ConnectAsync(endpoint);

            ReceiveLoop().Ignore();
            SendLoop().Ignore();
        }
Exemplo n.º 27
0
        public async Task Connect(string host, int port)
        {
            var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            await socket.ConnectAsync(host, port);

            var stream = new NetworkStream(socket, true);
            _currentSession = new SmppSession(stream, stream);
        }
 public override async Task<Stream> Open(string address)
 {
     var endPoint = new UnixDomainSocketEndPoint("/tmp/" + address);
     _socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Unspecified);
     await _socket.ConnectAsync(endPoint).ConfigureAwait(false);
     _networkStream = new NetworkStream(_socket);
     return _networkStream;
 }
Exemplo n.º 29
0
 public void connect()
 {
     m_socket.ConnectAsync(m_connectEventArg);//Begins an asynchronous request for a connection to a remote host.
     m_autoConnectSignal.WaitOne();
     Log.ASSERT("connect failed!", m_connectEventArg.SocketError == SocketError.Success);
     if (!m_socket.ReceiveAsync(m_receiveEventArg))
     {
         process_receive(m_receiveEventArg);
     }
 }
Exemplo n.º 30
0
        private void Form1_Load(object sender, EventArgs e)
        {
            m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10000); //포트 대기 설정
            //IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 10000); //포트 대기 설정
            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.RemoteEndPoint = ipep;

            m_ClientSocket.ConnectAsync(args);
        }
Exemplo n.º 31
0
 void Conncet(string IP_Address)
 {
     client_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs()
     {
         RemoteEndPoint = new IPEndPoint(IPAddress.Parse(IP_Address), 4531)
     };
     socketEventArg.Completed += OnConncetCompleted;
     client_socket.ConnectAsync(socketEventArg);
 }
Exemplo n.º 32
0
        public void ConnectAsync()
        {
            Initialised = true;
            
            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketAsyncEventArgs socketConnectionArgs = new SocketAsyncEventArgs();
            socketConnectionArgs.UserToken = m_serverEndPoint;
            socketConnectionArgs.RemoteEndPoint = m_serverEndPoint;
            socketConnectionArgs.Completed += SocketConnect_Completed;

            m_socket.ConnectAsync(socketConnectionArgs);
        }
Exemplo n.º 33
0
        public void Connect(string hostName, int portNumber)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var endPoint = new DnsEndPoint(hostName, portNumber);
            _socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = endPoint };

            SetMaxReceiveBufferSize(DefaultBufferSize);

            _socketEventArg.Completed += socketCommandCompleted;

            _socket.ConnectAsync(_socketEventArg);
        }
Exemplo n.º 34
0
 public TcpConnectSAE(Socket socket, IPEndPoint remote, DelegateConnected connected)
 {
     if (null == socket) throw new ArgumentException();
     this.socket = socket;
     if (null == remote) throw new ArgumentException();
     if (null == connected) throw new ArgumentException();
     this.connected = connected;
     SocketAsyncEventArgs sae = new SocketAsyncEventArgs();
     sae.Completed += sae_Completed;
     sae.RemoteEndPoint = remote;
     socket.ConnectAsync(sae);
 }
Exemplo n.º 35
0
		partial void SendTimeRequest()
		{
			try
			{
				byte[] buffer = new byte[48];
				buffer[0] = 0x1B;

				DnsEndPoint _endPoint = new DnsEndPoint(_ServerAddress, 123, AddressFamily.InterNetwork);
				Socket socket = null;
				var socketArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
				try
				{
					socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

					try
					{
						socketArgs.Completed += Socket_Completed_SendAgain;
						//TFW - For some reason 'ConnectAsync' reports an error
						//desktop .Net 4, but 'Connect' works fine. On WP
						//only ConnectAsync is available, and it appears to work.
#if USE_CONNECTASYNC
					socketArgs.SetBuffer(buffer, 0, buffer.Length);
					if (!socket.ConnectAsync(socketArgs))
						Socket_Completed_SendAgain(socket, socketArgs);
#else
						socket.Connect(socketArgs.RemoteEndPoint);
						socketArgs.SetBuffer(buffer, 0, buffer.Length);
						if (!socket.SendAsync(socketArgs))
							Socket_Completed_SendAgain(socket, socketArgs);
#endif
					}
					catch
					{
						socketArgs.Completed -= this.Socket_Completed_SendAgain;
						throw;
					}
				}
				catch
				{
					socket?.Dispose();
					throw;
				}
			}
			catch (SocketException se)
			{
				OnErrorOccurred(new NtpNetworkException(se.Message, (int)se.SocketErrorCode, se));
			}
			catch (Exception ex)
			{
				OnErrorOccurred(new NtpNetworkException(ex.Message, -1, ex));
			}
		}
Exemplo n.º 36
0
		public void Connect(string address, int port)
		{
			_totalBytesTransferred = 0;

			_endPoint = new DnsEndPoint(address, port);
			_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			
			SocketAsyncEventArgs args = new SocketAsyncEventArgs();
			args.UserToken = _socket;
			args.RemoteEndPoint = _endPoint;
			args.Completed += OnSocketCompleted;
			_socket.ConnectAsync(args);
		}
Exemplo n.º 37
0
        public static Socket Connect(IPEndPoint remoteEndpoint, TimeSpan connectTimeout)
        {
            var socket = new Socket(remoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) {NoDelay = true};

#if FEATURE_SOCKET_EAP
            var connectCompleted = new ManualResetEvent(false);
            var args = new SocketAsyncEventArgs
            {
                UserToken = connectCompleted,
                RemoteEndPoint = remoteEndpoint
            };
            args.Completed += ConnectCompleted;

            if (socket.ConnectAsync(args))
            {
                if (!connectCompleted.WaitOne(connectTimeout))
                    throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
                        "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds));
            }

            if (args.SocketError != SocketError.Success)
                throw new SocketException((int) args.SocketError);
            return socket;
#elif FEATURE_SOCKET_APM
            var connectResult = socket.BeginConnect(remoteEndpoint, null, null);
            if (!connectResult.AsyncWaitHandle.WaitOne(connectTimeout, false))
                throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
                    "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds));
            socket.EndConnect(connectResult);
            return socket;
#elif FEATURE_SOCKET_TAP
            if (!socket.ConnectAsync(remoteEndpoint).Wait(connectTimeout))
                throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
                    "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds));
            return socket;
#else
            #error Connecting to a remote endpoint is not implemented.
#endif
        }
Exemplo n.º 38
0
        private void Connect()
        {
            _endpoint = new DnsEndPoint("localhost", 4502);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();

            args.UserToken = _socket;
            args.RemoteEndPoint = _endpoint;
            args.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);

            _socket.ConnectAsync(args);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void Connect(String host, int port)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.NoDelay = true;
            _socket.Blocking = false;

            m_connectSaea = new SocketAsyncEventArgs();
            m_connectSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
            m_connectSaea.Completed += IOCompleted;

            if (!_socket.ConnectAsync(m_connectSaea))
                ProcessConnected();
        }
Exemplo n.º 40
0
        public async Task ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken = default)
        {
            if (this.socket != null)
            {
                throw new InvalidOperationException("Socket already established");
            }
            var socket = new System.Net.Sockets.Socket(SocketType.Stream, ProtocolType.Tcp);
            await socket.ConnectAsync(endPoint, cancellationToken);

            this.socket = socket;
            if (hasEvents)
            {
                ReceiveAsync();
            }
        }
Exemplo n.º 41
0
        protected sealed override async Task InternalOpenAsync(bool internalCall = false)
        {
            try
            {
                if (_shutdown || IsConnected)
                {
                    return;
                }
                await DisposeSocketAsync().ConfigureAwait(false);

                _identity = null;
                _socket   = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    ReceiveBufferSize = _configuration.ReceiveBufferSize,
                    NoDelay           = true
                };
                _logger?.LogDebug("Socket connecting. ({0}:{1})", _config.Hostname, _config.ServiceName);
                await _socket.ConnectAsync(_config.Hostname, _config.ServiceName).ConfigureAwait(false);

                EnsureConnected();
                _logger?.LogDebug("Socket connected. ({0}:{1})", _config.Hostname, _config.ServiceName);
                if (_config.KeepAlive)
                {
                    _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                }

                if (internalCall)
                {
                    EnableAutoReconnectReconnect();
                }

                _tokenSource   = new CancellationTokenSource();
                _receivingTask = Task.Factory.StartNew(() => StartReceive(), _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                await PublishConnectionStateChanged(true).ConfigureAwait(false);
            }
            catch (Exception)
            {
                await DisposeSocketAsync();
                await HandleSocketDown().ConfigureAwait(false);

                if (!internalCall)
                {
                    throw;
                }
            }
        }
Exemplo n.º 42
0
 public bool Connect()
 {
     if (Connected)
     {
         return(true);
     }
     try
     {
         mPackage.Reset();
         mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         if (!mSocket.ConnectAsync(mConnectSAEA))
         {
             OnConnected(this, mConnectSAEA);
         }
         return(mConnected);
     }
     catch (Exception e_)
     {
         mConnected = false;
         OnError(e_);
         return(false);
     }
 }
Exemplo n.º 43
0
        /// <summary>
        /// N개의 클라이언트를 서버에 연결한다.
        /// </summary>
        /// <param name="serverAddr"></param>
        /// <param name="port"></param>
        public void Connect(string serverAddr, int port, string playerSessionId, ENetState netState)
        {
            System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.LingerState    = new LingerOption(true, 10);
            socket.NoDelay        = true;
            socket.SendTimeout    = 1000;
            socket.ReceiveTimeout = 1000;


            _clientSession = new ClientSession(_logger, _bufferSize);
            _clientSession.CompletedMessageCallback += OnMessageCompleted;
            _clientSession.SessionId = playerSessionId;
            _clientSession.NetState  = netState;


            _serverAddr         = serverAddr;
            _gameSessionId      = string.Empty;
            _playerSessionId    = playerSessionId;
            _port               = port;
            _reconnectCheckTime = DateTime.UtcNow;


            _logger.Debug(string.Format("[NetClient] Connect to server. socketHandle: {0}, addr: {1}:{2}, playerSessionId: {3}, gameSessionId: {4}", socket.Handle, _serverAddr, _port, _playerSessionId, _gameSessionId));


            SocketAsyncEventArgs args = new SocketAsyncEventArgs();

            args.Completed     += OnConnectCompleted;
            args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(serverAddr), port);

            bool pendiing = socket.ConnectAsync(args);

            if (pendiing == false)
            {
                OnConnectCompleted(socket, args);
            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// Connects to the specified endpoint.
        /// </summary>
        /// <param name="endPoint">Endpoint to connect to.</param>
        public void Connect(IPEndPoint endPoint)
        {
            if (MainSocket != null && Session?.CurrentState != SocketSession <TSession, TConfig> .State.Closed)
            {
                throw new InvalidOperationException("Client is in the process of connecting.");
            }

            MainSocket = new System.Net.Sockets.Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true
            };

            // Set to true if the client connection either timed out or was canceled.
            bool timedOut = false;

            _connectionTimeoutCancellation = new CancellationTokenSource();

            _connectionTimeoutTask = new Task(async() =>
            {
                try
                {
                    await Task.Delay(Config.ConnectionTimeout, _connectionTimeoutCancellation.Token);
                }
                catch
                {
                    return;
                }

                timedOut = true;
                OnClose(null, SocketCloseReason.TimeOut);
                MainSocket.Close();
            });


            var eventArg = new SocketAsyncEventArgs
            {
                RemoteEndPoint = endPoint
            };

            eventArg.Completed += (sender, args) =>
            {
                if (timedOut)
                {
                    return;
                }
                if (args.LastOperation == SocketAsyncOperation.Connect)
                {
                    // Stop the timeout timer.
                    _connectionTimeoutCancellation.Cancel();

                    Session            = CreateSession(MainSocket);
                    Session.Connected += (sndr, e) => OnConnect(Session);

                    ConnectedSessions.TryAdd(Session.Id, Session);

                    ((ISetupSocketSession)Session).Start();
                }
            };


            MainSocket.ConnectAsync(eventArg);

            _connectionTimeoutTask.Start();
        }
 public static IAsyncResult BeginConnect(this System.Net.Sockets.Socket socket
                                         , System.Net.IPEndPoint remoteEP
                                         , AsyncCallback callback, object state)
 {
     return(socket.ConnectAsync(remoteEP).AsApm(callback, state));
 }
Exemplo n.º 46
0
 bool Utils.Wrappers.Interfaces.ISocket.ConnectAsync(SocketAsyncEventArgs e)
 {
     return(InternalSocket.ConnectAsync(e));
 }
Exemplo n.º 47
0
 public static Task ConnectAsync(this Socket socket, string host, int port) =>
 socket.ConnectAsync(host, port);
Exemplo n.º 48
0
        private static void ConnectAsync(IntPtr info)
        {
            NSJSFunctionCallbackInfo arguments = NSJSFunctionCallbackInfo.From(info);
            bool success = false;

            do
            {
                if (arguments.Length <= 0)
                {
                    Throwable.ObjectDisposedException(arguments.VirtualMachine);
                    break;
                }
                SocketContext context = GetSocketContext(arguments.This);
                if (context == null)
                {
                    Throwable.ObjectDisposedException(arguments.VirtualMachine);
                    break;
                }
                SOCKET socket = context.Socket;
                if (socket == null || SocketExtension.CleanedUp(socket))
                {
                    Throwable.ObjectDisposedException(arguments.VirtualMachine);
                    break;
                }
                EndPoint remoteEP = ObjectAuxiliary.ToEndPoint(arguments[0]);
                int      cbsolt   = 1;
                if (remoteEP == null)
                {
                    IPAddress address = ObjectAuxiliary.ToAddress(arguments[0]);
                    if (address == null)
                    {
                        break;
                    }
                    int port = arguments.Length > 1 ? ((arguments[1] as NSJSInt32)?.Value).GetValueOrDefault() : 0;
                    remoteEP = new IPEndPoint(address, port);
                    cbsolt++;
                }
                if (remoteEP == null)
                {
                    break;
                }
                NSJSFunction callback = arguments.Length > cbsolt ? arguments[cbsolt] as NSJSFunction : null;
                try
                {
                    SocketAsyncEventArgs e = context.ConnectedAsync;
                    if (e != null)
                    {
                        break;
                    }
                    else
                    {
                        e                      = new SocketAsyncEventArgs();
                        e.Completed           += ProcessConnected;
                        e.UserToken            = context;
                        context.ConnectedAsync = e;
                    }
                    e.RemoteEndPoint = remoteEP;
                    if (callback != null)
                    {
                        callback.CrossThreading        = true;
                        context.ConnectedAsyncCallback = callback;
                    }
                    if (!socket.ConnectAsync(e))
                    {
                        ProcessConnected(socket, e);
                    }
                    success = true;
                }
                catch (Exception e)
                {
                    Throwable.Exception(arguments.VirtualMachine, e);
                }
            } while (false);
            arguments.SetReturnValue(success);
        }
Exemplo n.º 49
0
        // --- ( Static ) Public Function ------------------------------------------------------------------------------------------------------------------------------------ //

        // --- ( Static ) Internal & Protected Function ---------------------------------------------------------------------------------------------------------------------- //

        // --- ( Static ) Private Function ----------------------------------------------------------------------------------------------------------------------------------- //

        // --- Public Function ----------------------------------------------------------------------------------------------------------------------------------------------- //

        // --- Internal & Protected Function --------------------------------------------------------------------------------------------------------------------------------- //

        // 创建套接字代理 ( 频道 )
        internal SocketAgent(string host, SocketChannel parentChannel)
        {
            InnerSocket   = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ParentChannel = parentChannel;
            // 解析主机地址
            string[] hostStrings = host.Split(":".ToCharArray());
            if (hostStrings.Length < 2 || !IPAddress.TryParse(hostStrings[0], out IPAddress ip) || !ushort.TryParse(hostStrings[1], out ushort port))
            {
                ERROR("Nero.ManageSocket.AddSocketChannel --- host 格式错误, 解析失败",
                      "channel : " + ParentChannel.ChannelIndex,
                      "host : " + ParentChannel.ChannelHost);
            }
            else
            {
                MessageListeners    = new List <SocketMessageListener> [65536];
                ReceiveBuffer       = BufferHandler.GetBuffer();
                SendArgs            = new SocketAsyncEventArgs();
                SendArgs.Completed += new EventHandler <SocketAsyncEventArgs>((object o, SocketAsyncEventArgs e) => {
                    if (e.SocketError == SocketError.Success)
                    {
                        SendMessageBody();
                    }
                    else
                    {
                        Disconnect();
                    }
                });
                ConnectArgs = new SocketAsyncEventArgs()
                {
                    RemoteEndPoint = new IPEndPoint(ip, port)
                };
                ConnectArgs.Completed += new EventHandler <SocketAsyncEventArgs>((object o, SocketAsyncEventArgs e) => {
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - LOCK ( SpinLock )
                    // Lock objects : SocketChannelHandler.DelayedOperations
                    LOCK(ref SocketChannelHandler.DelayedOperationsLockRoot);
                    try {
                        if (ConnectArgs.SocketError == SocketError.Success)
                        {
                            ConnectedCAS = 1;
                            SYSTEM("Socket Channel - 套接字频道连接成功", "Channel - " + ParentChannel.ChannelIndex, "Host - " + ParentChannel.ChannelHost);
                            // 添加套接字频道连接成功延迟操作
                            SocketChannelHandler.DelayedOperations.Add(new SocketChannelOperation()
                            {
                                Type         = DelayedOperationType.ConnectionCompleted,
                                ChannelIndex = ParentChannel.ChannelIndex
                            });
                        }
                        else
                        {
                            WARNING("Socket Channel - 套接字频道连接失败", "Channel - " + ParentChannel.ChannelIndex, "Host - " + ParentChannel.ChannelHost);
                            // 添加套接字频道连接失败延迟操作
                            SocketChannelHandler.DelayedOperations.Add(new SocketChannelOperation()
                            {
                                Type          = DelayedOperationType.ConnectionFailed,
                                ChannelIndex  = ParentChannel.ChannelIndex,
                                TargetChannel = ParentChannel
                            });
                        }
                    } finally { UNLOCK(ref SocketChannelHandler.DelayedOperationsLockRoot); }
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - UNLOCK ( SpinLock )
                    ConnectArgs.Dispose();
                });
                if (!InnerSocket.ConnectAsync(ConnectArgs))
                {
                    ConnectedCAS = 1;
                    SYSTEM("Socket Channel - 套接字频道连接成功", "Channel - " + ParentChannel.ChannelIndex, "Host - " + ParentChannel.ChannelHost);
                    // 添加套接字频道连接成功延迟操作 ( 同步完成, 无需重复进 SocketChannelHandler.DelayedOperations 锁 )
                    SocketChannelHandler.DelayedOperations.Add(new SocketChannelOperation()
                    {
                        Type         = DelayedOperationType.ConnectionCompleted,
                        ChannelIndex = ParentChannel.ChannelIndex
                    });
                    ConnectArgs.Dispose();
                }
            }
        }
        public bool start(string ip, int port, bool takon)
        {
            try
            {
                IP   = ip;
                PORT = port;
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                tcpc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //  tcpc.ExclusiveAddressUse = false;
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = new DnsEndPoint(IP, port);

                socketEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
                {
                    if (e.SocketError != SocketError.Success)
                    {
                        if (e.SocketError == SocketError.ConnectionAborted)
                        {
                            timeoutevent();

                            //Dispatcher.BeginInvoke(() => MessageBox.Show("连接超时请重试! " + e.SocketError));
                        }
                        else if (e.SocketError == SocketError.ConnectionRefused)
                        {
                            ErrorMge(0, "服务器端未启动");

                            //Dispatcher.BeginInvoke(() => MessageBox.Show("服务器端问启动" + e.SocketError));
                        }
                        else
                        {
                            ErrorMge(0, "出错了");
                            // Dispatcher.BeginInvoke(() => MessageBox.Show("出错了" + e.SocketError));
                        }
                    }
                    else
                    {
                        Isline = true;
                        isok   = true;
                        //if (NATUDP)
                        //{
                        //    udp.start(ip, new Random().Next(10000, 60000), port);
                        //    udp.send(0x9c, IPAddress.None.ToString() + ":" + port, localEndPoint);
                        //}
                        timeout = DateTime.Now;
                        if (!isreceives)
                        {
                            isreceives = true;
                            System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Receive));
                        }
                    }
                });

                tcpc.ConnectAsync(socketEventArg);
                int ss = 0;
                if (!takon)
                {
                    return(true);
                }
                while (Tokan == null)
                {
                    System.Threading.Thread.Sleep(1000);
                    ss++;
                    if (ss > 10)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                Isline = false;
                if (ErrorMge != null)
                {
                    ErrorMge(1, e.Message);
                }
                return(false);
            }
        }
Exemplo n.º 51
0
        /// <summary>
        /// Begin asynchronous connect.
        /// </summary>
        /// <param name="endPoint"></param>
        /// <returns></returns>
        public bool ConnectAsync(EndPoint endPoint)
        {
            lock (_syncRoot)
            {
                if (_asyncConnectArgs != null)
                {// Connection in progress.
                    return(true);
                }
            }

            System.Net.Sockets.Socket socket = _socket;
            if (IsConnected)
            {// Already connected.
                if (socket != null)
                {
                    try
                    {
                        if (socket.RemoteEndPoint.Equals(endPoint))
                        {// Connected to given endPoint.
                            return(true);
                        }
                        else
                        {// Connected to some other endPoint
                            ReleaseSocket(true);
                        }
                    }
                    catch (Exception ex)
                    {// socket.RemoteEndPoint can throw.
                        ReleaseSocket(true);
#if Matrix_Diagnostics
                        Monitor.OperationError("Failed to start async connect", ex);
#endif
                        return(false);
                    }
                }
            }

            SocketAsyncEventArgs args;
            lock (_syncRoot)
            {
                if (_asyncConnectArgs != null)
                {// Connection in progress.
                    return(true);
                }

                _socket = new System.Net.Sockets.Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                socket  = _socket;

                _asyncConnectArgs                = new SocketAsyncEventArgs();
                _asyncConnectArgs.Completed     += new EventHandler <SocketAsyncEventArgs>(SocketAsyncEventArgs_Connected);
                _asyncConnectArgs.RemoteEndPoint = endPoint;
                _endPoint = endPoint;
                args      = _asyncConnectArgs;
            }

            if (socket != null && socket.ConnectAsync(args) == false)
            {
                SocketAsyncEventArgs_Connected(this, args);
            }

            return(true);
        }
Exemplo n.º 52
0
 public static Task ConnectAsync(this Socket socket, IPAddress[] addresses, int port) =>
 socket.ConnectAsync(addresses, port);
Exemplo n.º 53
0
 public bool start(string ip, int port, bool takon)
 {
     try
     {
         int ss = 0;
         IP   = ip;
         PORT = port;
         IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
         tcpc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         //  tcpc.ExclusiveAddressUse = false;
         SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
         socketEventArg.RemoteEndPoint = new DnsEndPoint(IP, port);
         socketEventArg.Completed     += new EventHandler <SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
         {
             if (e.SocketError != SocketError.Success)
             {
                 ss = 999999;
                 if (e.SocketError == SocketError.ConnectionAborted)
                 {
                     timeoutevent();
                     //Dispatcher.BeginInvoke(() => MessageBox.Show("连接超时请重试! " + e.SocketError));
                 }
                 else if (e.SocketError == SocketError.ConnectionRefused)
                 {
                     if (ErrorMge != null)
                     {
                         ErrorMge(0, "服务器端未启动" + e.SocketError);
                     }
                     //Dispatcher.BeginInvoke(() => MessageBox.Show("服务器端问启动" + e.SocketError));
                 }
                 else
                 {
                     if (ErrorMge != null)
                     {
                         ErrorMge(0, "出错了" + e.SocketError);
                     }
                     // Dispatcher.BeginInvoke(() => MessageBox.Show("出错了" + e.SocketError));
                 }
             }
             else
             {
                 Isline  = true;
                 isok    = true;
                 timeout = DateTime.Now;
                 if (!isreceives)
                 {
                     isreceives = true;
                     Task.Factory.StartNew(() => { Receive(null); });
                     Task.Factory.StartNew(() => { unup(); });
                     //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Receive));
                 }
             }
         });
         tcpc.ConnectAsync(socketEventArg);
         if (!takon)
         {
             return(true);
         }
         while (Tokan == null)
         {
             System.Threading.Tasks.Task.Delay(10000000);
             if (ss > 0)
             {
                 return(false);
             }
         }
         return(true);
     }
     catch (Exception e)
     {
         Isline = false;
         if (ErrorMge != null)
         {
             ErrorMge(1, e.Message);
         }
         return(false);
     }
 }
Exemplo n.º 54
0
 public static Task ConnectAsync(this Socket socket, EndPoint remoteEP) =>
 socket.ConnectAsync(remoteEP);