SetToConnected() private method

private SetToConnected ( ) : void
return void
Example #1
0
        internal override object PostCompletion(int numBytes)
        {
            SocketError errorCode   = (SocketError)base.ErrorCode;
            Socket      asyncObject = (Socket)base.AsyncObject;

            if (errorCode == SocketError.Success)
            {
                try
                {
                    errorCode = UnsafeNclNativeMethods.OSSOCK.setsockopt(asyncObject.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateConnectContext, (byte[])null, 0);
                    if (errorCode == SocketError.SocketError)
                    {
                        errorCode = (SocketError)Marshal.GetLastWin32Error();
                    }
                }
                catch (ObjectDisposedException)
                {
                    errorCode = SocketError.OperationAborted;
                }
                base.ErrorCode = (int)errorCode;
            }
            if (errorCode == SocketError.Success)
            {
                asyncObject.SetToConnected();
                return(asyncObject);
            }
            return(null);
        }
Example #2
0
        // This method is called by base.CompletionPortCallback base.OverlappedCallback as part of IO completion
        internal override object PostCompletion(int numBytes)
        {
            SocketError errorCode = (SocketError)ErrorCode;
            Socket      socket    = (Socket)AsyncObject;

            if (errorCode == SocketError.Success)
            {
                // Set the socket context.
                try
                {
                    errorCode = Interop.Winsock.setsockopt(
                        socket.SafeHandle,
                        SocketOptionLevel.Socket,
                        SocketOptionName.UpdateConnectContext,
                        null,
                        0);
                    if (errorCode == SocketError.SocketError)
                    {
                        errorCode = (SocketError)Marshal.GetLastWin32Error();
                    }
                }
                catch (ObjectDisposedException)
                {
                    errorCode = SocketError.OperationAborted;
                }

                ErrorCode = (int)errorCode;
            }

            if (errorCode == SocketError.Success)
            {
                socket.SetToConnected();
                return(socket);
            }

            return(null);
        }
Example #3
0
        internal Socket UpdateAcceptSocket(Socket socket, EndPoint remoteEP)
        {
            // Internal state of the socket is inherited from listener.
            socket._addressFamily = _addressFamily;
            socket._socketType = _socketType;
            socket._protocolType = _protocolType;
            socket._rightEndPoint = _rightEndPoint;
            socket._remoteEndPoint = remoteEP;

            // The socket is connected.
            socket.SetToConnected();

            // if the socket is returned by an End(), the socket might have
            // inherited the WSAEventSelect() call from the accepting socket.
            // we need to cancel this otherwise the socket will be in non-blocking
            // mode and we cannot force blocking mode using the ioctlsocket() in
            // Socket.set_Blocking(), since it fails returing 10022 as documented in MSDN.
            // (note that the m_AsyncEvent event will not be created in this case.

            socket._willBlock = _willBlock;

            // We need to make sure the Socket is in the right blocking state
            // even if we don't have to call UnsetAsyncEventSelect
            socket.InternalSetBlocking(_willBlock);

            return socket;
        }
Example #4
0
        internal void FinishOperationSuccess(SocketError socketError, int bytesTransferred, SocketFlags flags)
        {
            SetResults(socketError, bytesTransferred, flags);

            switch (_completedOperation)
            {
            case SocketAsyncOperation.Accept:
                if (bytesTransferred > 0)
                {
                    // Log and Perf counters.
                    if (s_loggingEnabled)
                    {
                        LogBuffer(bytesTransferred);
                    }
                    if (Socket.s_perfCountersEnabled)
                    {
                        UpdatePerfCounters(bytesTransferred, false);
                    }
                }

                // Get the endpoint.
                Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);

                socketError = FinishOperationAccept(remoteSocketAddress);

                if (socketError == SocketError.Success)
                {
                    _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));

                    if (s_loggingEnabled)
                    {
                        SocketsEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
                    }
                }
                else
                {
                    SetResults(socketError, bytesTransferred, SocketFlags.None);
                    _acceptSocket = null;
                }
                break;

            case SocketAsyncOperation.Connect:
                if (bytesTransferred > 0)
                {
                    // Log and Perf counters.
                    if (s_loggingEnabled)
                    {
                        LogBuffer(bytesTransferred);
                    }
                    if (Socket.s_perfCountersEnabled)
                    {
                        UpdatePerfCounters(bytesTransferred, true);
                    }
                }

                socketError = FinishOperationConnect();

                // Mark socket connected.
                if (socketError == SocketError.Success)
                {
                    if (s_loggingEnabled)
                    {
                        SocketsEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
                    }

                    _currentSocket.SetToConnected();
                    _connectSocket = _currentSocket;
                }
                break;

            case SocketAsyncOperation.Disconnect:
                _currentSocket.SetToDisconnected();
                _currentSocket._remoteEndPoint = null;

                break;

            case SocketAsyncOperation.Receive:
                if (bytesTransferred > 0)
                {
                    // Log and Perf counters.
                    if (s_loggingEnabled)
                    {
                        LogBuffer(bytesTransferred);
                    }
                    if (Socket.s_perfCountersEnabled)
                    {
                        UpdatePerfCounters(bytesTransferred, false);
                    }
                }
                break;

            case SocketAsyncOperation.ReceiveFrom:
                if (bytesTransferred > 0)
                {
                    // Log and Perf counters.
                    if (s_loggingEnabled)
                    {
                        LogBuffer(bytesTransferred);
                    }
                    if (Socket.s_perfCountersEnabled)
                    {
                        UpdatePerfCounters(bytesTransferred, false);
                    }
                }

                // Deal with incoming address.
                _socketAddress.InternalSize = GetSocketAddressSize();
                Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
                if (!socketAddressOriginal.Equals(_socketAddress))
                {
                    try
                    {
                        _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
                    }
                    catch
                    {
                    }
                }
                break;

            case SocketAsyncOperation.ReceiveMessageFrom:
                if (bytesTransferred > 0)
                {
                    // Log and Perf counters.
                    if (s_loggingEnabled)
                    {
                        LogBuffer(bytesTransferred);
                    }
                    if (Socket.s_perfCountersEnabled)
                    {
                        UpdatePerfCounters(bytesTransferred, false);
                    }
                }

                // Deal with incoming address.
                _socketAddress.InternalSize = GetSocketAddressSize();
                socketAddressOriginal       = IPEndPointExtensions.Serialize(_remoteEndPoint);
                if (!socketAddressOriginal.Equals(_socketAddress))
                {
                    try
                    {
                        _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
                    }
                    catch
                    {
                    }
                }

                FinishOperationReceiveMessageFrom();
                break;

            case SocketAsyncOperation.Send:
                if (bytesTransferred > 0)
                {
                    // Log and Perf counters.
                    if (s_loggingEnabled)
                    {
                        LogBuffer(bytesTransferred);
                    }
                    if (Socket.s_perfCountersEnabled)
                    {
                        UpdatePerfCounters(bytesTransferred, true);
                    }
                }
                break;

            case SocketAsyncOperation.SendPackets:
                if (bytesTransferred > 0)
                {
                    // Log and Perf counters.
                    if (s_loggingEnabled)
                    {
                        LogSendPacketsBuffers(bytesTransferred);
                    }
                    if (Socket.s_perfCountersEnabled)
                    {
                        UpdatePerfCounters(bytesTransferred, true);
                    }
                }

                FinishOperationSendPackets();
                break;

            case SocketAsyncOperation.SendTo:
                if (bytesTransferred > 0)
                {
                    // Log and Perf counters.
                    if (s_loggingEnabled)
                    {
                        LogBuffer(bytesTransferred);
                    }
                    if (Socket.s_perfCountersEnabled)
                    {
                        UpdatePerfCounters(bytesTransferred, true);
                    }
                }
                break;
            }

            if (socketError != SocketError.Success)
            {
                // Asynchronous failure or something went wrong after async success.
                SetResults(socketError, bytesTransferred, flags);
                _currentSocket.UpdateStatusAfterSocketError(socketError);
            }

            // Complete the operation and raise completion event.
            Complete();
            if (_contextCopy == null)
            {
                OnCompleted(this);
            }
            else
            {
                ExecutionContext.Run(_contextCopy, _executionCallback, null);
            }
        }
Example #5
0
        //
        // CreateAcceptSocket - pulls unmanaged results and assembles them
        //   into a new Socket object
        //
        internal Socket CreateAcceptSocket(IntPtr fd, EndPoint remoteEP) {
            //
            // Internal state of the socket is inherited from listener
            //
            Socket socket           = new Socket(fd);
            socket.addressFamily    = addressFamily;
            socket.socketType       = socketType;
            socket.protocolType     = protocolType;
            socket.m_LocalEndPoint  = m_LocalEndPoint;
            socket.m_RemoteEndPoint = remoteEP;
            //
            // the socket is connected
            //
            socket.SetToConnected();
            //
            // if the socket is returned by an EndAccept(), the socket might have
            // inherited the WSAEventSelect() call from the accepting socket.
            // we need to cancel this otherwise the socket will be in non-blocking
            // mode and we cannot force blocking mode using the ioctlsocket() in
            // Socket.set_Blocking(), since it fails returing 10022 as documented in MSDN.
            // (note that the m_AsyncEvent event will not be created in this case.
            //
            socket.m_BlockEventBits = m_BlockEventBits;
            socket.SetAsyncEventSelect(AsyncEventBits.FdNone);
            //
            // the new socket will inherit the win32 blocking mode from the accepting socket.
            // if the user desired blocking mode is different from the win32 blocking mode
            // we need to force the desired blocking behaviour.
            //
            socket.willBlock = willBlock;
            if (willBlock!=willBlockInternal) {
                socket.InternalSetBlocking(willBlock);
            }

            return socket;
        }
Example #6
0
 internal Socket UpdateAcceptSocket(Socket socket, EndPoint remoteEP, bool needCancelSelect)
 {
     socket.addressFamily = this.addressFamily;
       socket.socketType = this.socketType;
       socket.protocolType = this.protocolType;
       socket.m_RightEndPoint = this.m_RightEndPoint;
       socket.m_RemoteEndPoint = remoteEP;
       socket.SetToConnected();
       socket.willBlock = this.willBlock;
       if (needCancelSelect)
     socket.UnsetAsyncEventSelect();
       else
     socket.InternalSetBlocking(this.willBlock);
       return socket;
 }
Example #7
0
        internal void FinishOperationSyncSuccess(int bytesTransferred, SocketFlags flags)
        {
            SetResults(SocketError.Success, bytesTransferred, flags);

            if (NetEventSource.IsEnabled || Socket.s_perfCountersEnabled)
            {
                LogBytesTransferred(bytesTransferred, _completedOperation);
            }

            SocketError socketError = SocketError.Success;

            switch (_completedOperation)
            {
            case SocketAsyncOperation.Accept:
                // Get the endpoint.
                Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);

                socketError = FinishOperationAccept(remoteSocketAddress);

                if (socketError == SocketError.Success)
                {
                    _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));

                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
                    }
                }
                else
                {
                    SetResults(socketError, bytesTransferred, flags);
                    _acceptSocket = null;
                    _currentSocket.UpdateStatusAfterSocketError(socketError);
                }
                break;

            case SocketAsyncOperation.Connect:
                socketError = FinishOperationConnect();
                if (socketError == SocketError.Success)
                {
                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
                    }

                    // Mark socket connected.
                    _currentSocket.SetToConnected();
                    _connectSocket = _currentSocket;
                }
                else
                {
                    SetResults(socketError, bytesTransferred, flags);
                    _currentSocket.UpdateStatusAfterSocketError(socketError);
                }
                break;

            case SocketAsyncOperation.Disconnect:
                _currentSocket.SetToDisconnected();
                _currentSocket._remoteEndPoint = null;
                break;

            case SocketAsyncOperation.ReceiveFrom:
                // Deal with incoming address.
                _socketAddress.InternalSize = GetSocketAddressSize();
                Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
                if (!socketAddressOriginal.Equals(_socketAddress))
                {
                    try
                    {
                        _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
                    }
                    catch
                    {
                    }
                }
                break;

            case SocketAsyncOperation.ReceiveMessageFrom:
                // Deal with incoming address.
                _socketAddress.InternalSize = GetSocketAddressSize();
                socketAddressOriginal       = IPEndPointExtensions.Serialize(_remoteEndPoint);
                if (!socketAddressOriginal.Equals(_socketAddress))
                {
                    try
                    {
                        _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
                    }
                    catch
                    {
                    }
                }

                FinishOperationReceiveMessageFrom();
                break;

            case SocketAsyncOperation.SendPackets:
                FinishOperationSendPackets();
                break;
            }

            Complete();
        }
Example #8
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());
        }
Example #9
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", "");

            //

            //
            // 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());
        }