Inheritance: LazyAsyncResult
コード例 #1
0
ファイル: ClientNetwork.cs プロジェクト: homerCourage/Network
        // block api
        public void Connect()
        {
            if (Connected)
                return;

            Log.Info("BeginReceive sysSocket.Connect(hostIp, hostPort);");
            try
            {
                sysSocket.Connect(hostIp, hostPort);
            }
            catch (Exception e)
            {
                Log.Error("ClientNetwork BeginReceive throw exp:{0}", e);
                defferedConnected = new ConnectAsyncResult()
                {
                    Ex = e,
                };

                return;
            }

            defferedConnected = new ConnectAsyncResult()
            {
                Conn = new Connector(sysSocket, 0),
            };
        }
コード例 #2
0
		public override IAsyncResult BeginConnect(System.Net.EndPoint endPoint, AsyncCallback callback, Object state)
		{
			ConnectAsyncResult lWrapper = new ConnectAsyncResult(callback, state);
			this.fInnerConnection.BeginConnect(endPoint, lWrapper.ConnectionConnect, this);

			return lWrapper;
		}
コード例 #3
0
ファイル: Socket.cs プロジェクト: REALTOBIZ/mono
        internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
        {
            if (CanUseConnectEx(remoteEP))
            {
                return BeginConnectEx(remoteEP, false, callback, state);
            }
            EndPoint endPointSnapshot = remoteEP;
            SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);

            // No context flow here.  Can use Lazy.
            ConnectAsyncResult asyncResult = new ConnectAsyncResult(this, endPointSnapshot, state, callback);
            DoBeginConnect(endPointSnapshot, socketAddress, asyncResult);
            return asyncResult;
        }
コード例 #4
0
ファイル: ClientNetwork.cs プロジェクト: homerCourage/Network
        public void Poll()
        {
            try
            {
                if (defferedConnected != null)
                {
                    connector = defferedConnected.Conn;
                    connector.BeginReceive();

                    // notify
                    if (ConnectorConnected != null)
                    {
                        ConnectorConnected(defferedConnected.Conn, defferedConnected.Ex);
                    }

                    defferedConnected = null;
                }

                RefreshMessageQueue();
                RefreshClient();
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
コード例 #5
0
ファイル: socket.cs プロジェクト: ArildF/masters
        //
        // Async Winsock Support, the following functions use either
        //   the Async Winsock support to do overlapped I/O WSASend/WSARecv
        //   or a WSAEventSelect call to enable selection and non-blocking mode
        //   of otherwise normal Winsock calls.
        //
        //   Currently the following Async Socket calls are supported:
        //      Send, Recv, SendTo, RecvFrom, Connect, Accept
        //

        /*++

        Routine Description:

           BeginConnect - Does a async winsock connect, by calling
           WSAEventSelect to enable Connect Events to signal an event and
           wake up a callback which involkes a callback.

            So note: This routine may go pending at which time,
            but any case the callback Delegate will be called upon completion

        Arguments:

           remoteEP - status line that we wish to parse
           Callback - Async Callback Delegate that is called upon Async Completion
           State - State used to track callback, set by caller, not required

        Return Value:

           IAsyncResult - Async result used to retreive result

        --*/

        /// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.BeginConnect"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state) {
            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            //
            // parameter validation
            //
            if (remoteEP==null) {
                throw new ArgumentNullException("remoteEP");
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginConnect() remoteEP:" + remoteEP.ToString());

            //
            // ask the EndPoint to generate a SocketAddress that we
            // can pass down to winsock
            //
            EndPoint endPointSnapshot = remoteEP;
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                endPointSnapshot = new IPEndPoint(((IPEndPoint)remoteEP).Address, ((IPEndPoint)remoteEP).Port);
            }
            SocketAddress socketAddress = endPointSnapshot.Serialize();

            // This will check the permissions for connect.
            CheckCacheRemote(socketAddress, endPointSnapshot, true);

            // get async going
            SetAsyncEventSelect(AsyncEventBits.FdConnect);

            ConnectAsyncResult asyncResult = new ConnectAsyncResult(this, state, callback);

            int errorCode =
                UnsafeNclNativeMethods.OSSOCK.connect(
                    m_Handle,
                    socketAddress.m_Buffer,
                    socketAddress.m_Size );

            if (errorCode!=SocketErrors.Success) {
                errorCode = Marshal.GetLastWin32Error();
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginConnect() UnsafeNclNativeMethods.OSSOCK.connect returns:" + errorCode.ToString());

            if (errorCode==SocketErrors.Success) {
                SetToConnected();
            }
            asyncResult.CheckAsyncCallResult(errorCode);

            //
            // if the asynchronous native call fails synchronously
            // we'll throw a SocketException
            //
            if (asyncResult.ErrorCode!=SocketErrors.Success) {
                //
                // update our internal state after this socket error and throw
                //
                UpdateStatusAfterSocketError();
                throw new SocketException(asyncResult.ErrorCode);
            }

            if (m_RightEndPoint==null) {
                //
                // save a copy of the EndPoint so we can use it for Create()
                //
                m_RightEndPoint = endPointSnapshot;
            }

            GlobalLog.Print( "BeginConnect() to:" + endPointSnapshot.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult));

            return asyncResult;
        }
コード例 #6
0
ファイル: Socket.cs プロジェクト: REALTOBIZ/mono
        public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
        {
            //
            //  parameter validation
            //
            if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "BeginConnect", remoteEP);

            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (remoteEP==null) {
                throw new ArgumentNullException("remoteEP");
            }

            if (isListening)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_sockets_mustnotlisten));
            }

            DnsEndPoint dnsEP = remoteEP as DnsEndPoint;
            if (dnsEP != null) 
            {
                if (dnsEP.AddressFamily != AddressFamily.Unspecified && !CanTryAddressFamily(dnsEP.AddressFamily)) 
                {
                    throw new NotSupportedException(SR.GetString(SR.net_invalidversion));
                }

                return BeginConnect(dnsEP.Host, dnsEP.Port, callback, state);
            }

            if (CanUseConnectEx(remoteEP))
            {
                return BeginConnectEx(remoteEP, true, callback, state);
            }

            // This will check the permissions for connect.
            EndPoint endPointSnapshot = remoteEP;
            SocketAddress socketAddress = CheckCacheRemote(ref endPointSnapshot, true);

            // Flow the context.  No need to lock it since we don't use it until the callback.
            ConnectAsyncResult asyncResult = new ConnectAsyncResult(this, endPointSnapshot, state, callback);
            asyncResult.StartPostingAsyncOp(false);

            // Post the connect.
            DoBeginConnect(endPointSnapshot, socketAddress, asyncResult);

            // We didn't throw, so finish the posting op.  This will call the callback if the operation already completed.
            asyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);

            if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "BeginConnect", asyncResult);
            return asyncResult;
        }
コード例 #7
0
ファイル: Socket.cs プロジェクト: korifey/hackathon-Ideaphone
 public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
 {
     if (Socket.s_LoggingEnabled)
     Logging.Enter(Logging.Sockets, (object) this, "BeginConnect", (object) remoteEP);
       if (this.CleanedUp)
     throw new ObjectDisposedException(this.GetType().FullName);
       if (remoteEP == null)
     throw new ArgumentNullException("remoteEP");
       if (this.isListening)
     throw new InvalidOperationException(SR.GetString("net_sockets_mustnotlisten"));
       DnsEndPoint dnsEndPoint = remoteEP as DnsEndPoint;
       if (dnsEndPoint != null)
       {
     if (dnsEndPoint.AddressFamily != AddressFamily.Unspecified && !this.CanTryAddressFamily(dnsEndPoint.AddressFamily))
       throw new NotSupportedException(SR.GetString("net_invalidversion"));
     else
       return this.BeginConnect(dnsEndPoint.Host, dnsEndPoint.Port, callback, state);
       }
       else
       {
     if (this.CanUseConnectEx(remoteEP))
       return this.BeginConnectEx(remoteEP, true, callback, state);
     EndPoint remoteEP1 = remoteEP;
     SocketAddress socketAddress = this.CheckCacheRemote(ref remoteEP1, true);
     ConnectAsyncResult connectAsyncResult = new ConnectAsyncResult((object) this, remoteEP1, state, callback);
     connectAsyncResult.StartPostingAsyncOp(false);
     this.DoBeginConnect(remoteEP1, socketAddress, (LazyAsyncResult) connectAsyncResult);
     connectAsyncResult.FinishPostingAsyncOp(ref this.Caches.ConnectClosureCache);
     if (Socket.s_LoggingEnabled)
       Logging.Exit(Logging.Sockets, (object) this, "BeginConnect", (object) connectAsyncResult);
     return (IAsyncResult) connectAsyncResult;
       }
 }
コード例 #8
0
ファイル: Socket.cs プロジェクト: korifey/hackathon-Ideaphone
 internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
 {
     if (this.CanUseConnectEx(remoteEP))
     return this.BeginConnectEx(remoteEP, false, callback, state);
       EndPoint remoteEP1 = remoteEP;
       SocketAddress socketAddress = this.SnapshotAndSerialize(ref remoteEP1);
       ConnectAsyncResult connectAsyncResult = new ConnectAsyncResult((object) this, remoteEP1, state, callback);
       this.DoBeginConnect(remoteEP1, socketAddress, (LazyAsyncResult) connectAsyncResult);
       return (IAsyncResult) connectAsyncResult;
 }
コード例 #9
0
ファイル: Socket.cs プロジェクト: charygao/corefx
        internal IAsyncResult UnsafeBeginConnect(IPEndPoint remoteEP, AsyncCallback callback, object state)
        {
            if (CanUseConnectEx(remoteEP))
            {
                return BeginConnectEx(remoteEP, false, callback, state);
            }

            EndPoint endPointSnapshot = remoteEP;
            var asyncResult = new ConnectAsyncResult(this, endPointSnapshot, state, callback);

            // For connectionless protocols, Connect is not an I/O call.
            Connect(remoteEP);
            asyncResult.FinishPostingAsyncOp();

            // Synchronously complete the I/O and call the user's callback.
            asyncResult.InvokeCallback();
            return asyncResult;
        }
コード例 #10
0
        //
        // This is the static internal callback that will be called when
        // the IO we issued for the user to winsock has completed, either
        // synchronously (Signaled=false) or asynchronously (Signaled=true)
        // when this function gets called it must:
        // 1) update the AsyncResult object with the results of the completed IO
        // 2) signal events that the user might be waiting on
        // 3) cal the callback function that the user might have specified
        //
        internal static void ConnectCallback(object stateObject, bool Signaled)
        {
            ConnectAsyncResult asyncResult = stateObject as ConnectAsyncResult;
            Socket             socket      = asyncResult.AsyncObject as Socket;

            GlobalLog.Enter("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback", "Signaled:" + Signaled.ToString());

            GlobalLog.Assert(!asyncResult.IsCompleted, "Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() asyncResult.IsCompleted", "");

            //
            // we now need to get the status of the async completion, we had an easy implementation
            // that uses GetSocketOption(), but VadimE suggested not to use this 'cause it may be
            // buggy on some platforms, so we use WSAEnumNetworkEvents() instead:
            //
            // The best way to do this is to call WSAEnumNetworkEvents and use the error code iError
            // array corresponding to FD_CONNECT. getsockopt (SO_ERROR) may return NO_ERROR under
            // stress even in case of error at least on Winnt4.0 (I don't remember whether I fixed
            // it on Win2000 or WinXP).
            //

            //
            // get async completion
            //

            /*
             * int errorCode = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
             * GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() GetSocketOption() returns errorCode:" + errorCode.ToString());
             */

            NetworkEvents networkEvents = new NetworkEvents();

            networkEvents.Events = AsyncEventBits.FdConnect;

            AutoResetEvent chkAsyncEvent = socket.m_AsyncEvent;

            int errorCode = SocketErrors.WSAENOTSOCK;

            if (chkAsyncEvent != null)
            {
                errorCode =
                    UnsafeNclNativeMethods.OSSOCK.WSAEnumNetworkEvents(
                        socket.m_Handle,
                        chkAsyncEvent.Handle,
                        ref networkEvents);

                if (errorCode != SocketErrors.Success)
                {
                    errorCode = Marshal.GetLastWin32Error();
                    GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() WSAEnumNetworkEvents() failed with errorCode:" + errorCode.ToString());
                }
                else
                {
                    errorCode = networkEvents.ErrorCodes[(int)AsyncEventBitsPos.FdConnectBit];
                    GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() ErrorCodes(FdConnect) got errorCode:" + errorCode.ToString());
                }
            }

            try {
                //
                // cancel async event
                //
                socket.SetAsyncEventSelect(AsyncEventBits.FdNone);
                //
                // go back to blocking mode
                //
                socket.InternalSetBlocking(true);
            }
            catch (Exception exception) {
                GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() caught exception::" + exception.Message);
                asyncResult.Result = exception;
            }

            //
            // if the native non-blocking call failed we'll throw a SocketException in EndConnect()
            //
            if (errorCode != SocketErrors.Success)
            {
                //
                // just save the error code, the SocketException will be thrown in EndConnect()
                //
                asyncResult.ErrorCode = errorCode;
            }
            else
            {
                //
                // the Socket is connected, update our state and performance counter
                //
                socket.SetToConnected();
            }

            //
            // call the user's callback now, if there is one.
            //
            asyncResult.InvokeCallback(false);

            GlobalLog.Leave("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback", errorCode.ToString());
        }
コード例 #11
0
ファイル: _connectasyncresult.cs プロジェクト: ydunk/masters
        //
        // This is the static internal callback that will be called when
        // the IO we issued for the user to winsock has completed, either
        // synchronously (Signaled=false) or asynchronously (Signaled=true)
        // when this function gets called it must:
        // 1) update the AsyncResult object with the results of the completed IO
        // 2) signal events that the user might be waiting on
        // 3) cal the callback function that the user might have specified
        //
        internal static void ConnectCallback(object stateObject, bool Signaled)
        {
            ConnectAsyncResult asyncResult = stateObject as ConnectAsyncResult;
            Socket             socket      = asyncResult.AsyncObject as Socket;

            GlobalLog.Enter("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback", "Signaled:" + Signaled.ToString());

            GlobalLog.Assert(!asyncResult.IsCompleted, "Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() asyncResult.IsCompleted", "");

            //

            //
            // get async completion
            //

            /*
             * int errorCode = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
             * GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() GetSocketOption() returns errorCode:" + errorCode.ToString());
             */

            NetworkEvents networkEvents = new NetworkEvents();

            networkEvents.Events = AsyncEventBits.FdConnect;

            AutoResetEvent chkAsyncEvent = socket.m_AsyncEvent;

            int errorCode = SocketErrors.WSAENOTSOCK;

            if (chkAsyncEvent != null)
            {
                errorCode =
                    UnsafeNclNativeMethods.OSSOCK.WSAEnumNetworkEvents(
                        socket.m_Handle,
                        chkAsyncEvent.Handle,
                        ref networkEvents);

                if (errorCode != SocketErrors.Success)
                {
                    errorCode = Marshal.GetLastWin32Error();
                    GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() WSAEnumNetworkEvents() failed with errorCode:" + errorCode.ToString());
                }
                else
                {
                    errorCode = networkEvents.ErrorCodes[(int)AsyncEventBitsPos.FdConnectBit];
                    GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() ErrorCodes(FdConnect) got errorCode:" + errorCode.ToString());
                }
            }

            try {
                //
                // cancel async event
                //
                socket.SetAsyncEventSelect(AsyncEventBits.FdNone);
                //
                // go back to blocking mode
                //
                socket.InternalSetBlocking(true);
            }
            catch (Exception exception) {
                GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() caught exception::" + exception.Message);
                asyncResult.Result = exception;
            }

            //
            // if the native non-blocking call failed we'll throw a SocketException in EndConnect()
            //
            if (errorCode != SocketErrors.Success)
            {
                //
                // just save the error code, the SocketException will be thrown in EndConnect()
                //
                asyncResult.ErrorCode = errorCode;
            }
            else
            {
                //
                // the Socket is connected, update our state and performance counter
                //
                socket.SetToConnected();
            }

            //
            // call the user's callback now, if there is one.
            //
            asyncResult.InvokeCallback(false);

            GlobalLog.Leave("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback", errorCode.ToString());
        }
コード例 #12
0
 internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
 {
     if (this.CanUseConnectEx(remoteEP))
     {
         return this.BeginConnectEx(remoteEP, false, callback, state);
     }
     EndPoint point = remoteEP;
     SocketAddress socketAddress = this.SnapshotAndSerialize(ref point);
     ConnectAsyncResult asyncResult = new ConnectAsyncResult(this, point, state, callback);
     this.DoBeginConnect(point, socketAddress, asyncResult);
     return asyncResult;
 }
コード例 #13
0
 public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
 {
     if (s_LoggingEnabled)
     {
         Logging.Enter(Logging.Sockets, this, "BeginConnect", remoteEP);
     }
     if (this.CleanedUp)
     {
         throw new ObjectDisposedException(base.GetType().FullName);
     }
     if (remoteEP == null)
     {
         throw new ArgumentNullException("remoteEP");
     }
     if (this.isListening)
     {
         throw new InvalidOperationException(SR.GetString("net_sockets_mustnotlisten"));
     }
     DnsEndPoint point = remoteEP as DnsEndPoint;
     if (point != null)
     {
         if ((point.AddressFamily != System.Net.Sockets.AddressFamily.Unspecified) && (point.AddressFamily != this.addressFamily))
         {
             throw new NotSupportedException(SR.GetString("net_invalidversion"));
         }
         return this.BeginConnect(point.Host, point.Port, callback, state);
     }
     if (this.CanUseConnectEx(remoteEP))
     {
         return this.BeginConnectEx(remoteEP, true, callback, state);
     }
     EndPoint point2 = remoteEP;
     SocketAddress socketAddress = this.CheckCacheRemote(ref point2, true);
     ConnectAsyncResult asyncResult = new ConnectAsyncResult(this, point2, state, callback);
     asyncResult.StartPostingAsyncOp(false);
     this.DoBeginConnect(point2, socketAddress, asyncResult);
     asyncResult.FinishPostingAsyncOp(ref this.Caches.ConnectClosureCache);
     if (s_LoggingEnabled)
     {
         Logging.Exit(Logging.Sockets, this, "BeginConnect", asyncResult);
     }
     return asyncResult;
 }