EndConnect() public method

public EndConnect ( IAsyncResult asyncResult ) : void
asyncResult IAsyncResult
return void
Esempio n. 1
0
 protected override void OnOpen(EventArgs e)
 {
     lock (this)
     {
         var proxy = this.m_tun2socks.Server;
         this.m_server = new Socket(proxy.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         this.m_server.BeginConnect(proxy, (ar) =>
         {
             bool closeing = false;
             try
             {
                 Socket socket = this.m_server;
                 if (ar == null || socket == null)
                 {
                     closeing = true;
                 }
                 else
                 {
                     socket.EndConnect(ar);
                     HandshakeToServerAsync();
                 }
             }
             catch (Exception)
             {
                 closeing = true;
             }
             if (closeing)
             {
                 this.Close();
             }
         }, null);
     }
 }
Esempio n. 2
0
        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));
        }
Esempio n. 3
0
        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));
        }
Esempio n. 4
0
        /// <summary>
        /// AsyncConnectCallback
        /// </summary>
        /// <param name="ar"></param>
        private void AsyncConnectCallback(IAsyncResult ar)
        {
            SocketState state = new SocketState();

            try
            {
                System.Net.Sockets.Socket handler = (System.Net.Sockets.Socket)ar.AsyncState;
                handler.EndConnect(ar);
                state            = new SocketState();
                state.workSocket = handler;
                //handler.SendTimeout = SendTimeOutMS;
                //handler.ReceiveTimeout = ReceiveTimeOutMS;

                Mark(string.Format("连接成功"));
                state.IsReceiveThreadAlive = true;
                statelst.Add(state);
                SetConnection(true, state);
                handler.BeginReceive(state.buffer, 0, 2, 0, new AsyncCallback(AsyncReceivedCallback), state);
            }
            catch (System.Net.Sockets.SocketException SktEx)
            {
                WriteLog(SktEx, SktEx.ErrorCode.ToString());
                SetConnection(false, state);
            }
            catch (Exception Ex)
            {
                WriteLog(Ex, Ex.Message);
                SetConnection(false, state);
            }
            finally
            {
                connectDone.Set();
            }
        }
Esempio n. 5
0
    private void OnConnect(IAsyncResult ar)
    {
        try {
            clientSocket.EndConnect(ar);
            // here we are connected, so we send login request!
            byte[]  bytesMsg;
            Message loginMsg = new Message(Command.Login, txtName.Text);
            bytesMsg = loginMsg.toByte();

            clientSocket.BeginSend(bytesMsg,
                                   0,
                                   bytesMsg.Length,
                                   SocketFlags.None,
                                   new AsyncCallback(OnSend),
                                   null);
            clientSocket.BeginReceive(byteData,
                                      0,
                                      byteData.Length,
                                      SocketFlags.None,
                                      new AsyncCallback(OnReceive),
                                      null);
        }
        catch (Exception ex) {
            log("Something went wrong during establishing connection:");
            log(ex.Message);
            btnConnect.Sensitive    = true;
            btnDisconnect.Sensitive = false;
            btnMsg.Sensitive        = false;
        }
    }
        /// <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 ();
            }
        }
Esempio n. 7
0
        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();
            }
        }
Esempio n. 8
0
        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;
            }
        }
Esempio n. 9
0
        /// <summary>
        /// 建立Tcp连接后处理函数
        /// </summary>
        /// <param name="iar">异步Socket</param>
        protected void Connected(IAsyncResult iar)
        {
            System.Net.Sockets.Socket socket = null;
            try
            {
                socket = (System.Net.Sockets.Socket)iar.AsyncState;
                socket.EndConnect(iar);

                //设置连接状态
                isConnection = true;
                //获取本机端口
                this._LoadProt = ((IPEndPoint)sock.LocalEndPoint).Port;
                //触发连接成功事件
                if (ClientConn != null)
                {
                    ClientConn("Success");
                }

                //判断是否开启心跳机制
                if (this.IsHeartbeat)
                {
                    if (Heartbeat_Thread == null)
                    {
                        HeartbeatTime    = DateTime.Now;
                        Heartbeat_Thread = new System.Threading.Thread(Heartbeat);
                        Heartbeat_Thread.IsBackground = true;
                        Heartbeat_Thread.Start();
                    }
                }
            }
            catch (SocketException e)
            {
                isConnection = false;
                //触发连接失败事件
                if (ClientConnCut != null)
                {
                    ClientConnCut("Fail-EX:" + e.Message);
                }
                return;
            }

            ///////////////////////////////////////////
            ///开启接收数据监控
            ///////////////////////////////////////////
            try
            {
                socket.BeginReceive(ReceiveDataBuffer, 0, ReceiveBufferSize, SocketFlags.None, new AsyncCallback(RecvData), socket);
            }
            catch (Exception e)
            {
                isConnection = false;
                //触发连接失败事件
                if (ClientConnCut != null)
                {
                    ClientConnCut("Fail-EX:" + e.Message);
                }
            }
        }
Esempio n. 10
0
 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);
 }
Esempio n. 11
0
        /**
         * Handles connection success or failure.
         *
         * @param asyncResult
         *  The IAsyncResult of the connection attempt.
         */
        public void ConnectionCallback(System.IAsyncResult asyncResult)
        {
            bool         connectionSuccess = true;
            ConnectState connectionState   = (ConnectState)asyncResult.AsyncState;

            try {
                penguinSocks.EndConnect(asyncResult);
            }catch {
                connectionSuccess = false;
            }
            connectionState.ConnectCallback(connectionState.Host, connectionState.Port, connectionSuccess);
        }
Esempio n. 12
0
 /// <summary>
 /// 连接的回调函数
 /// </summary>
 /// <param name="ar"></param>
 private void OnConnectCallBack(IAsyncResult ar)
 {
     if (!_socket.Connected)
     {
         return;
     }
     _socket.EndConnect(ar);
     if (ConnectCompleted != null)
     {
         ConnectCompleted(this, new SocketEventArgs());
     }
     StartReceive();
 }
Esempio n. 13
0
 /// <summary>
 /// Gets triggered when the socket reaches the connection endpoint
 /// </summary>
 /// <param name="ar">async result</param>
 private void OnConnectCallback(IAsyncResult ar)
 {
     try
     {
         _socket.EndConnect(ar);
         _connectedEvent.Set();
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.StackTrace);
         //throw new Exception("Couldn't connect to remote endpoint.\n" + e.Message); this exception can't be handled (async method)
     }
 }
Esempio n. 14
0
 public void Connect(string ip, int port, int timeout = 5000)
 {
     try
     {
         if (IsConnect())
             return;
         this.ip = ip;
         this.port = port;
         _remoteEP = new IPEndPoint(IPAddress.Parse(ip), port);
         if (_stateObject.Socket == null)
         {
             System.Net.Sockets.Socket handler = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             IAsyncResult asyncResult = handler.BeginConnect(_remoteEP, null, null);
             if (asyncResult.AsyncWaitHandle.WaitOne(timeout, true))
             {
                 handler.EndConnect(asyncResult);
                 _stateObject.Socket = handler;
                 var option = new TcpKeepAlive
                 {
                     OnOff = 1,
                     KeepAliveTime = 5000,
                     KeepAliveInterval = 1000
                 };
                 _stateObject.Socket.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null);
                 BeginReceive(_ioEvent);
                 OnConnected(_stateObject);
             }
             else
             {
                 _stateObject.Init();
                 throw new SocketException(10060);
             }
         }
         else
         {
             _stateObject.Init();
         }
     }
     catch (ArgumentNullException arg)
     {
         throw new Exception.Exception(arg.Message);
     }
     catch (SocketException se)
     {
         throw new Exception.Exception(se.Message);
     }
     catch (System.Exception e)
     {
         throw new Exception.Exception(e.Message);
     }
 }
Esempio n. 15
0
		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) {

			}
		}
Esempio n. 16
0
 void StartConnectingSocket(IPAddress addr, int port)
 {
     socket = new System.Net.Sockets.Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try {
         socket.BeginConnect(addr, port, (ar) => {
             try {
                 socket.EndConnect(ar);
                 loop.NonBlockInvoke(connectedCallback);
             } catch {
             }
         }, null);
     } catch {
     }
 }
Esempio n. 17
0
 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);
 }
Esempio n. 18
0
 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");
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Helper thread method to start the connection to peers
        /// </summary>
        /// <param name="state"></param>
        private void StartPeerConnectionThread(System.IAsyncResult result)
        {
            object[]        objs = (object[])result.AsyncState;
            Sockets.Socket  socket = (Sockets.Socket)objs[0];
            PeerInformation peerinfo = (PeerInformation)objs[1];
            ByteField20     infoDigest = new ByteField20(), peerId = new ByteField20();

            Sockets.NetworkStream netStream;

            try
            {
                socket.EndConnect(result);

                netStream = new Sockets.NetworkStream(socket, true);

                // send handshake info
                PeerProtocol.SendHandshake(netStream, this.infofile.InfoDigest);
                PeerProtocol.ReceiveHandshake(netStream, ref infoDigest);
                PeerProtocol.SendPeerId(netStream, this.mSession.LocalPeerID);

                if (!PeerProtocol.ReceivePeerId(netStream, ref peerId))
                {                 // NAT check
                    socket.Close();
                    return;
                }

                // check info digest matches and we are not attempting to connect to ourself
                if (infoDigest.Equals(this.infofile.InfoDigest) && !peerId.Equals(this.mSession.LocalPeerID))
                {
                    peerinfo.ID = peerId;
                    this.AddPeer(socket, netStream, peerinfo);
                }
                else                 // info digest doesn't match, close the connection
                {
                    socket.Close();
                }
            }
            catch (System.Exception e)
            {
                Config.LogException(e);
                // die if the connection failed
                if (socket != null)
                {
                    socket.Close();
                }
                return;
            }
        }
Esempio n. 20
0
        public void Open()
        {
            var  result  = _clientSocket.BeginConnect(IPAddress.Parse(_remoteIp), _remotePort, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(5000, true);

            if (_clientSocket.Connected)
            {
                _clientSocket.EndConnect(result);
            }
            else
            {
                _clientSocket.Close();
                throw new SocketException(10060);
            }
            //_clientSocket.Connect(IPAddress.Parse(_remoteIp), _remotePort);
        }
Esempio n. 21
0
        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!");
            }
        }
Esempio n. 22
0
        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);
        }
Esempio n. 23
0
 void StartConnectingSocket(IPAddress addr, int port)
 {
     socket = new System.Net.Sockets.Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try {
         socket.BeginConnect(addr, port, (ar) => {
             Enqueue(delegate {
                 try {
                     socket.EndConnect(ar);
                     connectedCallback();
                 } catch {
                 }
             });
         }, null);
     } catch {
     }
 }
Esempio n. 24
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.</param>
        public static void Connect(this System.Net.Sockets.Socket socket, EndPoint endpoint, TimeSpan timeout)
        {
            var result = socket.BeginConnect(endpoint, null, null);

            bool success = result.AsyncWaitHandle.WaitOne(timeout, true);

            if (success)
            {
                socket.EndConnect(result);
            }
            else
            {
                socket.Close();
                throw new SocketException(10060); // Connection timed out.
            }
        }
Esempio n. 25
0
        public static void Connect(this System.Net.Sockets.Socket socket, EndPoint endpoint, int timeout)
        {
            var result = socket.BeginConnect(endpoint, null, null);

            bool success = result.AsyncWaitHandle.WaitOne(timeout, true);

            if (socket.Connected)
            {
                socket.EndConnect(result);
            }
            else
            {
                socket.Close();
                throw new SocketException(ConnectionTimedOutStatusCode);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// 开始连接服务器
        /// </summary>
        /// <param name="port"></param>
        /// <param name="ip"></param>
        public void StartConnect(int port, string ip = "127.0.0.1")
        {
            try
            {
                mySocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress  address  = IPAddress.Parse(ip);
                IPEndPoint endPoint = new IPEndPoint(address, port);

                //开始异步连接
                mySocket.BeginConnect(endPoint, asyncResult =>
                {
                    try
                    {
                        mySocket.EndConnect(asyncResult);                        //结束异步连接
                        // localEndPointIp = mySocket.LocalEndPoint.ToString();     //得到ip地址

                        OnSuccess?.Invoke(this);   //连接成功的回调

                        recThread = new Thread(RecMsg);
                        recThread.IsBackground = true;
                        recThread.Start(mySocket);


                        Task.Run(() =>
                        {
                            while (true)
                            {
                                if (mySocket != null && IsReceive)
                                {
                                    string ss = EndPointIp;
                                    SendMsg("hear," + ss);
                                }
                                Thread.Sleep(HeartbeatCheckInterval);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        OnError?.Invoke(ex);
                    }
                }, null);
            }
            catch (Exception ex)
            {
                OnError?.Invoke(ex);    //报错的回调
            }
        }
Esempio n. 27
0
        /// <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);
            }
        }
Esempio n. 28
0
        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);
        }
Esempio n. 29
0
    public void OnConnected(IAsyncResult ar)
    {
        try
        {
            System.Net.Sockets.Socket sock = (System.Net.Sockets.Socket)ar.AsyncState;

            sock.EndConnect(ar);
            WriteLog("Connected to " + sock.RemoteEndPoint.ToString() + "\n", tagInfo);

            // Start receiving stuff
            Receive(sock);
        }
        catch (Exception ex)
        {
            WriteLog("Unable to connect to " + m_server_ip + ":" + m_server_port + "\n", tagInfo);
        }
    }
Esempio n. 30
0
        /// <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);
            }
        }
Esempio n. 31
0
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);

                Console.WriteLine("Socket connected to {0}",
                                  client.RemoteEndPoint.ToString());

                // Signal that the connection has been made.
                connectDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 32
0
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;

                callbacks[OpCodeReceive.ONCONNECT].call(null);

                // Complete the connection.
                client.EndConnect(ar);

                Debug.Log("Socket connected to " +
                          client.RemoteEndPoint.ToString());
                Receive(client);
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
Esempio n. 33
0
 /// <summary>
 /// socket连接返回函数
 /// </summary>
 /// <param name="ar">表示异步操作的状态</param>
 private void ConnectCallback(IAsyncResult ar)
 {
     try
     {
         // 获取socket连接实例
         System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;
         // 完成连接过程.
         client.EndConnect(ar);
         // 得到连接成功信息
         ConnectInfo    = "连接成功!";
         isTcpConnected = true;
         // 置位连接完成标志
         client_ConnectDone.Set();
     }
     catch (Exception e)
     {
         // 得到连接失败信息
         ConnectInfo = e.ToString();
         // 结束连接
         client_ConnectDone.Reset();
     }
 }
Esempio n. 34
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
        }
Esempio n. 35
0
        /// <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 );
        }
Esempio n. 36
0
        private void DoConnect(IAsyncResult ar)
        {
            System.Net.Sockets.Socket client = null;
            try
            {
                client = (System.Net.Sockets.Socket)ar.AsyncState;
                client.EndConnect(ar);
                _connectState = NetworkClientState.Connected;
                _msgCounter   = 0;
                Debug.Log("connect success!");
                if (_byteArray == null)
                {
                    _byteArray = new ByteArray();
                }
                _unityInvoke.Call((int p) =>
                {
                    if (onConnected != null)
                    {
                        onConnected.Invoke();
                    }
                }, 0);
            }
            catch (SocketException ex)
            {
                DoConnectError(ex);
                return;
            }

            try
            {
                StateObject obj = new StateObject(client);
                client.BeginReceive(obj.Buffer, 0, obj.Size, 0, DoReceive, obj);
            }
            catch (SocketException ex)
            {
                DoNetworkError(ex);
            }
        }
Esempio n. 37
0
        public void SendAsync(string message) {
            if (!client.Connected) {
                client.Shutdown(SocketShutdown.Both);
                client.Close();
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.BeginConnect(new IPEndPoint(IPAddress.Parse(Host), Port), ac => {
                    try {
                        client.EndConnect(ac);
                    }
                    catch (Exception ex) {
                        ExceptionAction(ex);
                    }

                    //send msg
                    SendMessageAsync(message);
                }, null);
            }
            else {
                //send msg
                SendMessageAsync(message);
            }

        }
Esempio n. 38
0
 public static void TcpConnect(IPAddress address, int port, Action<Exception, Socket> cb)
 {
     Socket sock = null;
     try {
         sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         sock.BeginConnect (address, port, (ar) => {
             try {
                 sock.EndConnect (ar);
                 sock.NoDelay = true;
             } catch (Exception ex) {
                 sock.Dispose ();
                 cb (ex, null);
                 return;
             }
             cb (null, sock);
         }, null);
     } catch (Exception ex) {
         if (sock != null)
             sock.Dispose ();
         cb (ex, null);
         return;
     }
 }
Esempio n. 39
0
        public static ISocket Open(string host, int port, TimeSpan connectTimeout)
        {
            var timeout = new ManualResetEvent(false);
            Exception connectFailure = null;
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var ar = socket.BeginConnect(host, port, r => {
                try {
                    socket.EndConnect(r);
                } catch(Exception e) {
                    connectFailure = e;
                } finally {
                    timeout.Set();
                }
            }, null);

            if(!timeout.WaitOne(connectTimeout)) {
                socket.EndConnect(ar);
                throw new TimeoutException();
            }
            if(connectFailure != null) {
                throw new ConnectException(connectFailure);
            }
            return new SocketAdapter(socket);
        }
Esempio n. 40
0
 private void onConnectionComplete(IAsyncResult ar)
 {
     try {
         _tempSocket = (Socket)ar.AsyncState;
         _tempSocket.EndConnect(ar);
         if (SocketConnected != null) {
             SocketConnected("null");
         }
         var socketState = new StateObject();
         socketState.WorkSocket = _tempSocket;
         _tempSocket.BeginReceive(socketState.Buffer, 0, socketState.BufferSize, 0, new AsyncCallback(onDataArrival), socketState);
     } catch (Exception ex) {
         if ((ex.Message.Contains("A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"))) {
             if (CouldNotConnect != null) {
                 CouldNotConnect(SocketID);
             }
         } else {
             if (SocketError != null) {
                 SocketError(ex);
             }
         }
     }
 }
Esempio n. 41
0
        private TestResult StdTestProcess(string addr, int timeout)
        {
            long pingTime = 0;

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

            try
            {
                var ar = socket.BeginConnect(addr, 443, x =>
                     {
                         try
                         {
                             socket.EndConnect(x);
                             pingTime = stopwatch.ElapsedMilliseconds;
                         }
                         catch (Exception) { }

                     }, null);

                stopwatch.Start();

                while (!ar.IsCompleted)
                {
                    if (stopwatch.ElapsedMilliseconds > TestTimeout)
                    {
                        stopwatch.Stop();
                        socket.Close();

                        return new TestResult()
                        {
                            addr = addr,
                            ok = false,
                            msg = "Timeout"
                        };
                    }

                    Thread.Sleep(20);
                }

                stopwatch.Stop();

                if (!socket.Connected)
                {
                    socket.Close();
                    return new TestResult()
                    {
                        addr = addr,
                        ok = false,
                        msg = "Failed"
                    };
                }

                socket.Close();
            }
            catch (Exception)
            {
                socket.Close();

                return new TestResult()
                {
                    addr = addr,
                    ok = false,
                    msg = "Failed"
                };
            }

            TestResult result;

            var sbd = new StringBuilder();

            for (int i = 0; i < 150; i++)
                sbd.Append(random.Next().ToString("D10"));

            var url = "https://" + addr + "/?" + Convert.ToBase64String(Encoding.UTF8.GetBytes(sbd.ToString()));

            var req = (HttpWebRequest)WebRequest.Create(url);
            req.Timeout = timeout;
            req.Method = "HEAD";
            req.AllowAutoRedirect = false;
            req.KeepAlive = false;
            req.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);

            try
            {
                using (var resp = (HttpWebResponse)req.GetResponse())
                {
                    if (resp.Server == "gws")
                    {
                        result = new TestResult()
                        {
                            addr = addr,
                            ok = true,
                            msg = "_OK " + pingTime.ToString("D4")
                        };
                    }
                    else
                    {
                        result = new TestResult()
                          {
                              addr = addr,
                              ok = false,
                              msg = "Invalid"
                          };
                    }
                    resp.Close();
                }
            }
            catch (Exception)
            {
                result = new TestResult()
                         {
                             addr = addr,
                             ok = false,
                             msg = "Failed"
                         };
            }

            return result;
        }
Esempio n. 42
0
        public void ConnectDeviceThread()
        {
            string ip = "";

            lock (this)//拿出一个IP
            {
                foreach (var IP in DeviceIP)
                {
                    if (IP.Value.Length == 0)
                    {
                        ip = IP.Key;
                        break;
                    }
                }
                DeviceIP[ip] = "Connecting";
            }
            bool       TimeOut   = false;                                                                                 //超时标志
            bool       Connected = false;                                                                                 //已经连接上标志
            string     Resourt   = "";
            IPEndPoint ipe       = new IPEndPoint(IPAddress.Parse(ip), 8086);                                             //把ip和端口转化为IPEndpoint实例
            //创建socket并连接到服务器
            Socket           c             = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建Socket
            ManualResetEvent TimeoutObject = new ManualResetEvent(false);

            TimeoutObject.Reset();
            c.BeginConnect(ipe, asyncResult => //开始链接
            {                                  //链接完毕后
                try
                {
                    if (TimeOut)//如果超时了才进入 则立刻退出
                    {
                        throw new System.Exception("Connect time out");
                    }
                    c.EndConnect(asyncResult);
                    if (c.Connected)
                    {
                        //向服务器发送信息
                        Log.Info("tcp:" + ip, "Send message start");
                        string sendStr = "AreYouThere";
                        byte[] bs      = Encoding.ASCII.GetBytes(sendStr); //把字符串编码为字节
                        c.Send(bs, bs.Length, 0);                          //发送信息
                        Log.Info("tcp:" + ip, "Send message complete");
                        ///接受从服务器返回的信息
                        string recvStr   = "";
                        byte[] recvBytes = new byte[1024];
                        int bytes;
                        try
                        {
                            c.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 600);
                            bytes    = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                            recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                        }
                        catch //接收确认信息超时 立刻退出
                        {
                            throw new System.Exception("ReceiveTimeOut");
                        }
                        Resourt = recvStr;
                        Log.Info("tcp:" + ip, "Get essage:" + recvStr); //显示服务器返回信息
                        if (recvStr.Contains("AAA"))                    //获得了正确的确认信息
                        {
                            Connected = true;
                            lock (this)
                            {
                                Device device    = new Device();//加入这个设备
                                device.DevIp     = ip;
                                device.DevSocket = c;
                                Devices.Add(device);
                            }
                            new Java.Lang.Thread(ConmmunityDeviceThread).Start();//启动一个与当前设备通信的进程
                        }
                    }
                    else//没链接上时 立刻退出
                    {
                        throw new System.Exception("No connect");
                    }
                }
                catch (System.Exception e)
                {
                    Log.Error("tcp:" + ip, e.Message);//显示服务器返回信息
                    Resourt = e.Message;
                }
                finally
                {
                    lock (this)
                    {
                        DeviceIP[ip] = Resourt;
                    }
                    //使阻塞的线程继续
                    TimeoutObject.Set();
                }
            }, c);
            //阻塞当前线程
            if (!TimeoutObject.WaitOne(700, false))
            {                                           //链接超时
                if (Connected == false)                 //未连接上
                {
                    Log.Error("tcp:" + ip, "Time out"); //显示服务器返回信息
                    TimeOut = true;
                    c.Close();
                }
            }
            if (TheardComplete++ >= ConnectDeviceTheardNum)
            {
                TheardComplete = 0;     //清空完成线程数
                FLAG_Scaning   = false; //关闭扫描中标志 可以开启下一次扫描
            }
        }
Esempio n. 43
0
    IEnumerator RestoreUpdate()
    {
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            Log.LogInfo("connect time out");
            MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
            yield break;
        }
        else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
        {
            //3G Tip
        }
        //Restore DownLoad From Progress.xml
        System.Net.Sockets.Socket         sClient     = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP);
        System.Net.EndPoint               server      = new System.Net.IPEndPoint(Dns.GetHostAddresses(GameData.Domain)[0], System.Convert.ToInt32(strPort));
        System.Threading.ManualResetEvent connectDone = new System.Threading.ManualResetEvent(false);
        try
        {
            connectDone.Reset();
            sClient.BeginConnect(server, delegate(IAsyncResult ar) {
                try
                {
                    System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;
                    client.EndConnect(ar);
                }
                catch (System.Exception e)
                {
                    Log.LogInfo(e.Message + "|" + e.StackTrace);
                }
                finally
                {
                    connectDone.Set();
                }
            }
                                 , sClient);
            //timeout
            if (!connectDone.WaitOne(2000))
            {
                Log.LogInfo("connect time out");
                MainLoader.ChangeStep(LoadStep.CannotConnect);
                yield break;
            }
            else
            {
                if (!sClient.Connected)
                {
                    Log.LogInfo("connect disabled by server");
                    MainLoader.ChangeStep(LoadStep.CannotConnect);
                    yield break;
                }
            }
        }
        catch
        {
            sClient.Close();
            MainLoader.ChangeStep(LoadStep.CannotConnect);
            yield break;
        }
        finally
        {
            connectDone.Close();
        }
        //Log.LogInfo("download:" + string.Format(strVFile, strHost, strPort, strProjectUrl, strPlatform, strVFileName));
        using (WWW vFile = new WWW(string.Format(strVFile, strHost, strPort, strProjectUrl, strPlatform, strVFileName)))
        {
            //Log.LogInfo("error:" + vFile.error);
            yield return(vFile);

            if (vFile.error != null && vFile.error.Length != 0)
            {
                //Log.LogInfo("error " + vFile.error);
                vFile.Dispose();
                //not have new version file
                //can continue game
                MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
                yield break;
            }
            if (vFile.bytes != null && vFile.bytes.Length != 0)
            {
                File.WriteAllBytes(strUpdatePath + "/" + "v.zip", vFile.bytes);
                DeCompressFile(strUpdatePath + "/" + "v.zip", strUpdatePath + "/" + "v.xml");
                vFile.Dispose();
            }
            else
            {
                MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
                yield break;
            }
        }

        XmlDocument xmlVer = new XmlDocument();

        xmlVer.Load(strUpdatePath + "/" + "v.xml");
        XmlElement ServerVer = xmlVer.DocumentElement;

        if (ServerVer != null)
        {
            string strServer = ServerVer.GetAttribute("ServerV");
            UpdateClient = HttpManager.AllocClient(string.Format(strDirectoryBase, strHost, strPort, strProjectUrl, strPlatform, strServer, ""));
            //if (strServer != null && GameData.Version().CompareTo(strServer) == -1)
            //{
            //	strServerVer = strServer;
            //	foreach (XmlElement item in ServerVer)
            //	{
            //		string strClientV = item.GetAttribute("ClientV");
            //		if (strClientV == GameData.Version())
            //		{
            //			strUpdateFile = item.GetAttribute("File");
            //			break;
            //		}
            //	}

            //	if (strUpdateFile != null && strUpdateFile.Length != 0)
            //		StartCoroutine("DownloadNecessaryData");
            //}
            //else
            //{
            //	Log.LogInfo("not need update");
            //             MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
            //}
        }
    }
Esempio n. 44
0
        public override Stream CreateStream()
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.NoDelay = true;
            socket.LingerState = new LingerOption(false, 0);

            IAsyncResult asyncResult = socket.BeginConnect(m_ipEndPoint, null, null);

            if (asyncResult.AsyncWaitHandle.WaitOne(2000, false))
            {
                socket.EndConnect(asyncResult);
            }
            else
            {
                socket.Close();
                throw new IOException("Connect failed");
            }

            AsyncNetworkStream stream = new AsyncNetworkStream(socket, true);

            return stream;
        }    
Esempio n. 45
0
 void Utils.Wrappers.Interfaces.ISocket.EndConnect(System.IAsyncResult asyncResult)
 {
     InternalSocket.EndConnect(asyncResult);
 }
Esempio n. 46
0
		public TdsComm (string dataSource, int port, int packetSize, int timeout, TdsVersion tdsVersion)
		{
			this.packetSize = packetSize;
			this.tdsVersion = tdsVersion;
			this.dataSource = dataSource;

			outBuffer = new byte[packetSize];
			inBuffer = new byte[packetSize];

			outBufferLength = packetSize;
			inBufferLength = packetSize;

			lsb = true;
			
			IPEndPoint endPoint;
			bool have_exception = false;
			
			try {
#if NET_2_0
				IPAddress ip;
				if(IPAddress.TryParse(this.dataSource, out ip)) {
					endPoint = new IPEndPoint(ip, port);
				} else {
					IPHostEntry hostEntry = Dns.GetHostEntry (this.dataSource);
					endPoint = new IPEndPoint(hostEntry.AddressList [0], port);
				}
#else
				IPHostEntry hostEntry = Dns.Resolve (this.dataSource);
				endPoint = new IPEndPoint (hostEntry.AddressList [0], port);
#endif
			} catch (SocketException e) {
				throw new TdsInternalException ("Server does not exist or connection refused.", e);
			}

			try {
				socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				IAsyncResult ares = socket.BeginConnect (endPoint, null, null);
				int timeout_ms = timeout * 1000;
				if (timeout > 0 && !ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (timeout_ms, false))
					throw Tds.CreateTimeoutException (dataSource, "Open()");
				socket.EndConnect (ares);
				try {
					// MS sets these socket option
					socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
				} catch (SocketException) {
					// Some platform may throw an exception, so
					// eat all socket exception, yeaowww! 
				}

				try {
#if NET_2_0
					socket.NoDelay = true;
#endif
					socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout_ms);
					socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout_ms);
				} catch {
					// Ignore exceptions here for systems that do not support these options.
				}
				// Let the stream own the socket and take the pleasure of closing it
				stream = new NetworkStream (socket, true);
			} catch (SocketException e) {
				have_exception = true;
				throw new TdsInternalException ("Server does not exist or connection refused.", e);
			} catch (Exception) {
				have_exception = true;
				throw;
			} finally {
				if (have_exception && socket != null) {
					try {
						Socket s = socket;
						socket = null;
						s.Close ();
					} catch {}
				}
			}
			if (!socket.Connected)
				throw new TdsInternalException ("Server does not exist or connection refused.", null);
			packetsSent = 1;
		}
 private static Task ConnectAsync(Socket socket, IPEndPoint endPoint)
 {
     return Task.Factory.FromAsync((cb, state) => socket.BeginConnect(endPoint, cb, state), ar => socket.EndConnect(ar), null);
 }
Esempio n. 48
0
		public void EndConnect ()
		{
			IPAddress ipOne = IPAddress.Parse (BogusAddress);
			IPEndPoint ipEP = new IPEndPoint (ipOne, BogusPort);
			Socket sock = new Socket (ipEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
			IAsyncResult ar = sock.BeginConnect (ipEP, null, null);

			try {
				// should raise an exception because connect was bogus
				sock.EndConnect (ar);
				Assert.Fail ("#1");
			} catch (SocketException ex) {
				Assert.AreEqual (10060, ex.ErrorCode, "#2");
			}
		}
Esempio n. 49
0
        private void ConnectToIP(IPAddress ipAddress)
        {
            IPEndPoint endpoint = new IPEndPoint(ipAddress, this.port);

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

            try
            {
                socket.BeginConnect(endpoint, r =>
                {
                    try
                    {
                        socket.EndConnect(r);
                    }
                    catch (SocketException)
                    {
                        this.OnError(socket);
                        return;
                    }

                    this.connectionInspector.SafeConnectionMade();
                    this.connectionMadeCallback(socket);
                }, state: null);
            }
            catch (SocketException)
            {
                this.OnError(socket);
            }
        }
Esempio n. 50
0
        public void RawOpen(int timeout)
        {
            // Keep track of time remaining; Even though there may be multiple timeout-able calls,
            // this allows us to still respect the caller's timeout expectation.
            var attemptStart = DateTime.Now;
            var result = Dns.BeginGetHostAddresses(Host, null, null);

            if (!result.AsyncWaitHandle.WaitOne(timeout, true))
            {
                // Timeout was used up attempting the Dns lookup
                throw new TimeoutException(L10N.DnsLookupTimeout);
            }

            timeout -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);

            var ips = Dns.EndGetHostAddresses(result);
            Socket socket = null;
            Exception lastSocketException = null;

            // try every ip address of the given hostname, use the first reachable one
            // make sure not to exceed the caller's timeout expectation by splitting the
            // time we have left between all the remaining ip's in the list.
            for (var i = 0; i < ips.Length; i++)
            {
                _log.Trace("Attempting to connect to " + ips[i]);
                var ep = new IPEndPoint(ips[i], Port);
                socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                attemptStart = DateTime.Now;

                try
                {
                    result = socket.BeginConnect(ep, null, null);

                    if (!result.AsyncWaitHandle.WaitOne(timeout / (ips.Length - i), true))
                    {
                        throw new TimeoutException(L10N.ConnectionTimeout);
                    }

                    socket.EndConnect(result);

                    // connect was successful, leave the loop
                    break;
                }
                catch (Exception e)
                {
                    _log.Warn("Failed to connect to " + ips[i]);
                    timeout -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);
                    lastSocketException = e;

                    socket.Close();
                    socket = null;
                }
            }

            if (socket == null)
            {
                throw lastSocketException;
            }

            var baseStream = new NpgsqlNetworkStream(socket, true);
            Stream sslStream = null;

            // If the PostgreSQL server has SSL connectors enabled Open SslClientStream if (response == 'S') {
            if (SSL || (SslMode == SslMode.Require) || (SslMode == SslMode.Prefer))
            {
                baseStream
                    .WriteInt32(8)
                    .WriteInt32(80877103);

                // Receive response
                var response = (Char)baseStream.ReadByte();

                if (response != 'S')
                {
                    if (SslMode == SslMode.Require) {
                        throw new InvalidOperationException(L10N.SslRequestError);
                    }
                }
                else
                {
                    //create empty collection
                    var clientCertificates = new X509CertificateCollection();

                    //trigger the callback to fetch some certificates
                    DefaultProvideClientCertificatesCallback(clientCertificates);

                    //if (context.UseMonoSsl)
                    if (!UseSslStream)
                    {
                        var sslStreamPriv = new SslClientStream(baseStream, Host, true, SecurityProtocolType.Default, clientCertificates)
                        {
                            ClientCertSelectionDelegate = DefaultCertificateSelectionCallback,
                            ServerCertValidationDelegate = DefaultCertificateValidationCallback,
                            PrivateKeyCertSelectionDelegate = DefaultPrivateKeySelectionCallback
                        };

                        sslStream = sslStreamPriv;
                        IsSecure = true;
                    }
                    else
                    {
                        var sslStreamPriv = new SslStream(baseStream, true, DefaultValidateRemoteCertificateCallback);
                        sslStreamPriv.AuthenticateAsClient(Host, clientCertificates, System.Security.Authentication.SslProtocols.Default, false);
                        sslStream = sslStreamPriv;
                        IsSecure = true;
                    }
                }
            }

            Socket = socket;
            BaseStream = baseStream;
            //Stream = new BufferedStream(sslStream ?? baseStream, 8192);
            Stream = BaseStream;
            Buffer = new NpgsqlBuffer(Stream, BufferSize, PGUtil.UTF8Encoding);
            _log.DebugFormat("Connected to {0}:{1 }", Host, Port);
        }
Esempio n. 51
0
        //Called trough reflection by CrossDomainPolicyParser.dll
        static Stream GetPolicyStreamForIP(string ip, int policyport, int timeout)
        {
            session++;
            Log("Incoming GetPolicyStreamForIP");
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ip), policyport);

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

            byte[] bytes = new byte[5000];

            var ms = new MemoryStream();
            int bytesRec;

            try
            {
                Log("About to BeginConnect to " + remoteEP);
                var async = sender.BeginConnect(remoteEP, null, null, false);
                Log("About to WaitOne");
                var start = DateTime.Now;
                if (!async.AsyncWaitHandle.WaitOne(timeout))
                {
                    Log("WaitOne timed out. Duration: " + (DateTime.Now - start).TotalMilliseconds);
                    sender.Close();
                    throw new Exception("BeginConnect timed out");
                }
                sender.EndConnect(async);

                Log("Socket connected");

                // Encode the data string into a byte array.
                byte[] msg = Encoding.ASCII.GetBytes(policy_request);

                SocketError error;

                // Send the data through the socket.
                sender.Send_nochecks(msg, 0, msg.Length, SocketFlags.None, out error);
                if (SocketError.Success != error)
                {
                    Log("Socket error: " + error);
                    return(ms);
                }

                // Receive the response from the remote device.
                bytesRec = sender.Receive_nochecks(bytes, 0, bytes.Length, SocketFlags.None, out error);
                if (SocketError.Success != error)
                {
                    Log("Socket error: " + error);
                    return(ms);
                }


                // Release the socket.
                try
                {
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (SocketException)
                {
                    //sometimes the connection closes before we can close it, that's fine.
                }
                ms = new MemoryStream(bytes, 0, bytesRec);
            }
            catch (Exception e)
            {
                Log("Caught exception: " + e.Message);
                //something went wrong, we'll just return an empty stream
                return(ms);
            }

            ms.Seek(0, SeekOrigin.Begin);

            return(ms);
        }
Esempio n. 52
0
 protected override int End(System.Net.Sockets.Socket socket, IAsyncResult ar)
 {
     socket.EndConnect(ar);
     return(0);
 }
Esempio n. 53
0
		/// <summary>
		/// Opens a new SocketStream
		/// </summary>
		internal static SocketStream Connect(string remoteSocket, int port, out int errno, out string errstr,
		  double timeout, SocketOptions flags, StreamContext/*!*/ context)
		{
			errno = 0;
			errstr = null;

			if (remoteSocket == null)
			{
				PhpException.ArgumentNull("remoteSocket");
				return null;
			}

			// TODO: extract schema (tcp://, udp://) and port from remoteSocket
			// Uri uri = Uri.TryCreate(remoteSocket);
			ProtocolType protocol = ProtocolType.Tcp;

			if (Double.IsNaN(timeout))
				timeout = Configuration.Local.FileSystem.DefaultSocketTimeout;

			// TODO:
			if (flags != SocketOptions.None && flags != SocketOptions.Asynchronous)
				PhpException.ArgumentValueNotSupported("flags", (int)flags);

			try
			{
                // workitem 299181; for remoteSocket as IPv4 address it results in IPv6 address
                //IPAddress address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];
                
                IPAddress address;
                if (!IPAddress.TryParse(remoteSocket, out address)) // if remoteSocket is not a valid IP address then lookup the DNS
                    address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];

				Socket socket = new Socket(address.AddressFamily, SocketType.Stream, protocol);

				IAsyncResult res = socket.BeginConnect(
				  new IPEndPoint(address, port),
				  new AsyncCallback(StreamSocket.ConnectResultCallback),
				  socket);

				int msec = 0;
				while (!res.IsCompleted)
				{
					Thread.Sleep(100);
					msec += 100;
					if (msec / 1000.0 > timeout)
					{
						PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_timeout",
						  FileSystemUtils.StripPassword(remoteSocket)));
						return null;
					}
				}
				socket.EndConnect(res);

				//        socket.Connect(new IPEndPoint(address, port));
				return new SocketStream(socket, remoteSocket, context, (flags & SocketOptions.Asynchronous) == SocketOptions.Asynchronous);
			}
			catch (SocketException e)
			{
				errno = e.ErrorCode;
				errstr = e.Message;
			}
			catch (System.Exception e)
			{
				errno = -1;
				errstr = e.Message;
			}

			PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_error",
			  FileSystemUtils.StripPassword(remoteSocket), errstr));
			return null;
		}
Esempio n. 54
0
        protected override Stream OpenStream(FileAccess access, FileShare sharing)
        {
            // Give the consumer a chance to set socket options
            OnConfigureSocket();

            // Is the socket already connected?
            if (_Socket == null || !_Socket.Connected)
            {
                // Close any exsisting socket
                if (_Socket != null)
                    _Socket.Close();

                // Create a socket 
                _Socket = new Socket(_AddressFamily, _SocketType, _ProtocolType);

#if !PocketPC
                // A smaller buffer size reduces latency.  We want to process data as soon as it's transmitted
                _Socket.ReceiveBufferSize = NmeaReader.IdealNmeaBufferSize;
                _Socket.SendBufferSize = NmeaReader.IdealNmeaBufferSize;

                // Specify the timeout for read/write ops
                _Socket.ReceiveTimeout = 10000; // (int)DefaultReadTimeout.TotalMilliseconds;
                _Socket.SendTimeout = 10000; // = (int)DefaultWriteTimeout.TotalMilliseconds;
#endif
                // Begin connecting asynchronously
                IAsyncResult connectResult = _Socket.BeginConnect(_EndPoint, null, null);

                // Wait up to the timeout for the connection to complete
                if (!connectResult.AsyncWaitHandle.WaitOne((int)_DefaultConnectTimeout.TotalMilliseconds, false))
                    throw new TimeoutException(Name + " could not connect within the timeout period.");

                _Socket.EndConnect(connectResult);
            }

            // Wrap a network stream around the socket. 
            return new NetworkStream(_Socket, access, true);

            // We don't need to set the streams timeouts because they are implied by the 
            // socket timeouts set above.

            /* 
             * This is documented (see Socket.Shutdown()). Closed sockets shouldn't be 
             * reopened. Above, a non null socket wasn't being closed, which caused errors
             * suggesting that attempts were being made to reopen a socket.
             *
             * We also don't need to set the streams timeouts because they are implied by the 
             * socket timeouts.
             */

            #region Flip-floppy ownership

            //#if PocketPC

//            /* EXTREMELY IMPORTANT
//             * 
//             * The .NET implementation of the Socket and NetworkStream classes is such that
//             * any attempt to close a socket will prevent all future connection attempts!
//             * I'm not sure exactly why, but I believe that a simple close is inadvertantly
//             * shutting down the entire Bluetooth socket system.  This appears to only
//             * affect the Compact Framework.
//             * 
//             * As a result, it's very important to leave "ownsSocket" as FALSE.
//             */

//            return new NetworkStream(_Socket, access, false);
//            //                                        ^^^^^ very important to be False.
//#else
//            // And wrap a network stream around it
//            NetworkStream result = new NetworkStream(_Socket, access, true);

//            // Specify read/write timeouts
//            result.ReadTimeout = Convert.ToInt32(DefaultReadTimeout.TotalMilliseconds);
//            result.WriteTimeout = Convert.ToInt32(DefaultWriteTimeout.TotalMilliseconds);

//            return result;
//#endif

            #endregion

        }
Esempio n. 55
0
 public virtual void EndConnect(IAsyncResult ar)
 {
     fDataSocket.EndConnect(ar);
 }
Esempio n. 56
0
 private void EndConnectCore(Socket socket, IAsyncResult asyncResult) =>
 socket.EndConnect(asyncResult);
Esempio n. 57
0
 public void EndConnect(IAsyncResult asyncResult)
 {
     _clientSocket.EndConnect(asyncResult);
     _active = true;
 }
Esempio n. 58
0
		public void BogusEndConnect ()
		{
			IPAddress ipOne = IPAddress.Parse (BogusAddress);
			IPEndPoint ipEP = new IPEndPoint (ipOne, BogusPort);
			Socket sock = new Socket (ipEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
			IAsyncResult ar = sock.BeginConnect (ipEP, null, null);

			try {
				// should raise an exception because connect was bogus
				sock.EndConnect (ar);
				Assert.Fail ("#1");
			} catch (SocketException ex) {
				// Actual error code depends on network configuration.
				var error = (SocketError) ex.ErrorCode;
				Assert.That (error == SocketError.TimedOut ||
				             error == SocketError.ConnectionRefused ||
				             error == SocketError.NetworkUnreachable ||
				             error == SocketError.HostUnreachable, "#2");
			}
		}
Esempio n. 59
0
 public void EndConnect(IAsyncResult asyncResult)
 {
     client.EndConnect(asyncResult);
 }