Inheritance: System.ComponentModel.Win32Exception
Ejemplo n.º 1
0
 /// <summary>
 /// The Channel layer normalizes exceptions thrown by the underlying networking implementations
 /// into subclasses of CommunicationException, so that Channels can be used polymorphically from
 /// an exception handling perspective.
 /// </summary>
 internal static CommunicationException ConvertTransferException(SocketException socketException)
 {
     return new CommunicationException(
         string.Format(CultureInfo.CurrentCulture, 
         "A Udp error ({0}: {1}) occurred while transmitting data.", socketException.ErrorCode, socketException.Message), 
         socketException);
 }
Ejemplo n.º 2
0
        private void OnDisconnect(/*OPTIONAL*/ SocketException socketException)
        {
            // This handles disconnects if, for example, the app exits

            // If we have any waiting operations, we want to abort them
            List<WaitingOperationDescriptor> operationsToAbort = null;
            lock (_waitingOperations)
            {
                operationsToAbort = new List<WaitingOperationDescriptor>(_waitingOperations.Values);
                _waitingOperations.Clear();
            }
            foreach (var operation in operationsToAbort)
            {
                if (socketException == null)
                {
                    operation.Abort();
                }
                else
                {
                    operation.OnSocketError(socketException);
                }
            }

            // Otherwise just drop the connection
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Determines if the exception thrown is a <see cref="SocketException"/> meaning that the connection was closed by the other side.
        /// </summary>
        public static bool IsConnectionAbortedByTheOtherSide(SocketException socketEx)
        {
            if (socketEx == null)
                throw new ArgumentNullException("socketEx");

            return ConnectionClosedErrors.Contains(socketEx.SocketErrorCode);
        }
Ejemplo n.º 4
0
        void Complete(SocketAsyncEventArgs e, bool completeSynchronously)
        {
            TransportBase transport = null;
            Exception exception = null;
            if (e.SocketError != SocketError.Success)
            {
                exception = new SocketException((int)e.SocketError);
                if (e.AcceptSocket != null)
                {
                    e.AcceptSocket.Close(0);
                }
            }
            else
            {
                Fx.Assert(e.AcceptSocket != null, "Must have a valid socket accepted.");
                transport = new TcpTransport(e.AcceptSocket, this.transportSettings);
                transport.Open();
            }

            e.Dispose();
            this.callbackArgs.CompletedSynchronously = completeSynchronously;
            this.callbackArgs.Exception = exception;
            this.callbackArgs.Transport = transport;

            if (!completeSynchronously)
            {
                this.callbackArgs.CompletedCallback(this.callbackArgs);
            }
        }
Ejemplo n.º 5
0
        public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
        {
            TimeoutObject.Reset();
            socketexception = null;

            string serverip = Convert.ToString(remoteEndPoint.Address);
            int serverport = remoteEndPoint.Port;
            TcpClient tcpclient = new TcpClient();

            tcpclient.BeginConnect(serverip, serverport,
                new AsyncCallback(CallBackMethod), tcpclient);

            if (TimeoutObject.WaitOne(timeoutMSec, false))
            {
                if (IsConnectionSuccessful)
                {
                    return tcpclient;
                }
                else
                {
                    throw socketexception;
                }
            }
            else
            {
                tcpclient.Close();
                throw new TimeoutException("TimeOut Exception");
            }
        }
Ejemplo n.º 6
0
            unsafe public void Run(object state)
            {
                byte[] address = new byte [1024];
                int    size    = 1024;
                Errno  errno;

                fixed(byte *ptr = address)
                do
                {
                    accepted = accept(socket, ptr,
                                      ref size);
                    errno = Stdlib.GetLastError();
                } while ((int)accepted == -1 &&
                         errno == Errno.EINTR);

                if ((int)accepted == -1)
                {
                    except = GetException(errno);
                }

                completed = true;

                if (waithandle != null)
                {
                    waithandle.Set();
                }

                if (callback != null)
                {
                    callback(this);
                }
            }
Ejemplo n.º 7
0
        public static unsafe SafeCloseSocket CreateSocket(SocketInformation socketInformation, out AddressFamily addressFamily, out SocketType socketType, out ProtocolType protocolType)
        {
            SafeCloseSocket handle;
            Interop.Winsock.WSAPROTOCOL_INFO protocolInfo;

            fixed (byte* pinnedBuffer = socketInformation.ProtocolInformation)
            {
                handle = SafeCloseSocket.CreateWSASocket(pinnedBuffer);
                protocolInfo = (Interop.Winsock.WSAPROTOCOL_INFO)Marshal.PtrToStructure<Interop.Winsock.WSAPROTOCOL_INFO>((IntPtr)pinnedBuffer);
            }

            if (handle.IsInvalid)
            {
                SocketException e = new SocketException();
                if (e.SocketErrorCode == SocketError.InvalidArgument)
                {
                    throw new ArgumentException(SR.net_sockets_invalid_socketinformation, "socketInformation");
                }
                else
                {
                    throw e;
                }
            }

            addressFamily = protocolInfo.iAddressFamily;
            socketType = (SocketType)protocolInfo.iSocketType;
            protocolType = (ProtocolType)protocolInfo.iProtocol;
            return handle;
        }
Ejemplo n.º 8
0
        private async Task <SocketMessage> InternalReceiveAsync()
        {
            if (this.Closed)
            {
                throw new SocketException((int)SocketError.NotConnected);
            }

            SocketMessage msg = null;

            try
            {
                using (BinaryReader streamReader = new BinaryReader(this.Stream, Encoding.UTF8, true))
                {
                    int    len   = streamReader.ReadInt32();
                    byte[] block = streamReader.ReadBytes(len);

                    object result  = this.Serializer.ReadObject(new MemoryStream(block));
                    var    wrapper = result as MessageWrapper;
                    if (wrapper != null && wrapper.Message is SocketMessage)
                    {
                        msg = (SocketMessage)wrapper.Message;
                        if (msg.Id == DisconnectMessageId)
                        {
                            // client is politely saying good bye...
                            this.OnClosed();
                        }
                        else if (msg.Id == ConnectedMessageId)
                        {
                            // must send an acknowledgement of the connect message
                            this.Name = msg.Sender;
                            await this.SendAsync(new SocketMessage(MessageAck, this.Name));
                        }
                        else if (msg.Id == OpenBackChannelMessageId && this.Server != null)
                        {
                            // client is requesting a back channel.
                            await this.HandleBackchannelRequest(msg);
                        }
                    }
                }
            }
            catch (EndOfStreamException)
            {
                this.OnClosed();
            }
            catch (System.IO.IOException ioe)
            {
                System.Net.Sockets.SocketException se = ioe.InnerException as System.Net.Sockets.SocketException;
                if (se.SocketErrorCode == SocketError.ConnectionReset)
                {
                    this.OnClosed();
                }
            }
            catch (Exception ex)
            {
                this.OnError(ex);
            }

            return(msg);
        }
Ejemplo n.º 9
0
    bool IsWouldBlockException(SocketException e)
    {
#if CF
      return (e.NativeErrorCode == 10035);
#else
      return (e.SocketErrorCode == SocketError.WouldBlock);
#endif
    }
Ejemplo n.º 10
0
    bool IsTimeoutException(SocketException e)
    {
#if CF
       return (e.NativeErrorCode == 10060);
#else
      return (e.SocketErrorCode == SocketError.TimedOut);
#endif
    }
Ejemplo n.º 11
0
        internal static IPAddress Parse(string ipString, bool tryParse)
        {
            if (ipString == null)
            {
                if (tryParse)
                {
                    return null;
                }
                throw new ArgumentNullException("ipString");
            }

            uint error = 0;

            // IPv6 Changes: Detect probable IPv6 addresses and use separate parse method.
            if (ipString.IndexOf(':') != -1)
            {
                // If the address string contains the colon character
                // then it can only be an IPv6 address. Use a separate
                // parse method to unpick it all. Note: we don't support
                // port specification at the end of address and so can
                // make this decision.
                uint scope;
                byte[] bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
                error = IPAddressPal.Ipv6StringToAddress(ipString, bytes, out scope);

                if (error == IPAddressPal.SuccessErrorCode)
                {
                    // AppCompat: .Net 4.5 ignores a correct port if the address was specified in brackets.
                    // Will still throw for an incorrect port.
                    return new IPAddress(bytes, (long)scope);
                }
            }
            else
            {
                ushort port;
                byte[] bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
                error = IPAddressPal.Ipv4StringToAddress(ipString, bytes, out port);

                if (error == IPAddressPal.SuccessErrorCode)
                {
                    if (port != 0)
                    {
                        throw new FormatException(SR.dns_bad_ip_address);
                    }

                    return new IPAddress(bytes);
                }
            }

            if (tryParse)
            {
                return null;
            }

            Exception e = new SocketException(IPAddressPal.GetSocketErrorForErrorCode(error), error);
            throw new FormatException(SR.dns_bad_ip_address, e);
        }
Ejemplo n.º 12
0
        public int Connect(ref ArraySegment <byte> readBuffer, IList <ArraySegment <byte> > writeBuffer)
        {
            if (_state == StateNeedConnect)
            {
                _state = StateConnectPending;
                return(SocketOperation.Connect);
            }
            else if (_state <= StateConnectPending)
            {
                Debug.Assert(_writeEventArgs != null);
                if (_writeEventArgs.SocketError != SocketError.Success)
                {
                    var ex = new System.Net.Sockets.SocketException((int)_writeEventArgs.SocketError);
                    if (Network.ConnectionRefused(ex))
                    {
                        throw new ConnectionRefusedException(ex);
                    }
                    else
                    {
                        throw new ConnectFailedException(ex);
                    }
                }
                Debug.Assert(_fd != null);
                _desc  = Network.FdToString(_fd, _proxy, _addr);
                _state = _proxy != null ? StateProxyWrite : StateConnected;
            }

            if (_state == StateProxyWrite)
            {
                Debug.Assert(_proxy != null);
                Debug.Assert(_addr != null);
                _proxy.BeginWrite(_addr, writeBuffer);
                return(SocketOperation.Write);
            }
            else if (_state == StateProxyRead)
            {
                Debug.Assert(_proxy != null);
                readBuffer = _proxy.BeginRead();
                return(SocketOperation.Read);
            }
            else if (_state == StateProxyConnected)
            {
                Debug.Assert(_proxy != null);
                _proxy.Finish(readBuffer);

                // TODO Return buffers to the pool
                readBuffer = ArraySegment <byte> .Empty;
                writeBuffer.Clear();

                _state = StateConnected;
            }

            Debug.Assert(_state == StateConnected);
            return(SocketOperation.None);
        }
Ejemplo n.º 13
0
        public int initialize()
        {
            if(_state == StateNeedConnect)
            {
                _state = StateConnectPending;
                return SocketOperation.Connect;
            }
            else if(_state <= StateConnectPending)
            {
                try
                {
#if ICE_SOCKET_ASYNC_API
                    if(_writeEventArgs.SocketError != SocketError.Success)
                    {
                        SocketException ex = new SocketException((int)_writeEventArgs.SocketError);
                        if(Network.connectionRefused(ex))
                        {
                            throw new Ice.ConnectionRefusedException(ex);
                        }
                        else
                        {
                            throw new Ice.ConnectFailedException(ex);
                        }
                    }
#else
                    Network.doFinishConnectAsync(_fd, _writeResult);
                    _writeResult = null;
#endif
                    _state = StateConnected;
                    _desc = Network.fdToString(_fd);
                }
                catch(Ice.LocalException ex)
                {
                    if(_traceLevels.network >= 2)
                    {
                        System.Text.StringBuilder s = new System.Text.StringBuilder();
                        s.Append("failed to establish tcp connection\n");
                        s.Append(Network.fdLocalAddressToString(_fd));
                        Debug.Assert(_addr != null);
                        s.Append("\nremote address = " + _addr.ToString() + "\n");
                        s.Append(ex.ToString());
                        _logger.trace(_traceLevels.networkCat, s.ToString());
                    }
                    throw;
                }

                if(_traceLevels.network >= 1)
                {
                    string s = "tcp connection established\n" + _desc;
                    _logger.trace(_traceLevels.networkCat, s);
                }
            }
            Debug.Assert(_state == StateConnected);
            return SocketOperation.None;
        }
Ejemplo n.º 14
0
        private void RecvCallback_obsolete(IAsyncResult ar)
        {
            try
            {
                if (RemoteState != null)
                {
                    if (RemoteState.Stream.CanRead)
                    {
                        int len = RemoteState.Stream.EndRead(ar);
                        if (len == 0)
                        {
                            Disconnect();
                        }
                        else
                        {
                            string data = "";
                            if (ProtocolStrategy != null)
                            {
                                data = ProtocolStrategy.Encoding.GetString(RemoteState.ReadBuffer, 0, len);
                                ProtocolStrategy.Parse(data, null);
                            }

                            RemoteState.Stream.BeginRead(RemoteState.ReadBuffer, 0, RemoteState.ReadBuffer.Length, new AsyncCallback(RecvCallback_obsolete), null);
                        }
                    }
                }
                else
                {
                }
            }
            catch (System.IO.IOException ioe)
            {
                if (ioe.InnerException.GetType() == typeof(System.Net.Sockets.SocketError))
                {
                    System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ioe.InnerException;

                    try
                    {
                        Disconnect();
                    }
                    catch (NullReferenceException)
                    { }
                    catch (Exception e)
                    {
                        OnAsyncException(new ExceptionEventArgs(e));
                    }
                }
            }
            catch (NullReferenceException)
            { }
            catch (Exception e)
            {
                OnAsyncException(new ExceptionEventArgs(e));
            }
        }
        protected bool ValidateAsyncResult(SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                var socketException = new SocketException((int)e.SocketError);
                OnCompleted(new ProxyEventArgs(new Exception(socketException.Message, socketException)));
                return false;
            }

            return true;
        }
Ejemplo n.º 16
0
 static ErrorType HandleDnsLookupError( string context, SocketException se )
 {
     switch( se.SocketErrorCode ) {
     case SocketError.HostNotFound:
     case SocketError.NoData:
         return ErrorType.PermanentKnown;
     default:
         Debug.WriteLine( string.Format( "WARNING: Unexpected SocketException with SocketErrorCode=={0} in {1}", Enum.GetName(typeof(SocketError),se.SocketErrorCode), context ) );
         return ErrorType.TemporaryUnknown;
     }
 }
 public static Exception ConvertListenException(SocketException socketException, IPEndPoint localEndpoint)
 {
     if (socketException.ErrorCode == 6)
     {
         return new CommunicationObjectAbortedException(socketException.Message, socketException);
     }
     if (socketException.ErrorCode == 0x2740)
     {
         return new AddressAlreadyInUseException(System.ServiceModel.SR.GetString("TcpAddressInUse", new object[] { localEndpoint.ToString() }), socketException);
     }
     return new CommunicationException(System.ServiceModel.SR.GetString("TcpListenError", new object[] { socketException.ErrorCode, socketException.Message, localEndpoint.ToString() }), socketException);
 }
Ejemplo n.º 18
0
 void HandleIOException(System.IO.IOException ioe, RemoteHostState state)
 {
     if (ioe.InnerException.GetType() == typeof(System.Net.Sockets.SocketError))
     {
         System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ioe.InnerException;
         CloseConnection(state, (se.SocketErrorCode == SocketError.Interrupted) ? null : se);
     }
     else
     {
         CloseConnection(state, ioe);
     }
 }
 internal ServerMockReceivedEventArgs( SocketAsyncEventArgs context )
 {
     this._context = context;
     if ( context.SocketError != SocketError.Success )
     {
         this._socketException = new SocketException( ( int )context.SocketError );
     }
     else
     {
         this._socketException = null;
     }
 }
Ejemplo n.º 20
0
        public int connect(Buffer readBuffer, Buffer writeBuffer, ref bool moreData)
        {
            if(_state == StateNeedConnect)
            {
                _state = StateConnectPending;
                return SocketOperation.Connect;
            }
            else if(_state <= StateConnectPending)
            {
#if ICE_SOCKET_ASYNC_API
                if(_writeEventArgs.SocketError != SocketError.Success)
                {
                    SocketException ex = new SocketException((int)_writeEventArgs.SocketError);
                    if(Network.connectionRefused(ex))
                    {
                        throw new Ice.ConnectionRefusedException(ex);
                    }
                    else
                    {
                        throw new Ice.ConnectFailedException(ex);
                    }
                }
#else
                Network.doFinishConnectAsync(_fd, _writeResult);
                _writeResult = null;
#endif
                _desc = Network.fdToString(_fd, _proxy, _addr);
                _state = _proxy != null ? StateProxyWrite : StateConnected;
            }

            if(_state == StateProxyWrite)
            {
                _proxy.beginWrite(_addr, writeBuffer);
                return SocketOperation.Write;
            }
            else if(_state == StateProxyRead)
            {
                _proxy.beginRead(readBuffer);
                return SocketOperation.Read;
            }
            else if(_state == StateProxyConnected)
            {
                _proxy.finish(readBuffer, writeBuffer);

                readBuffer.clear();
                writeBuffer.clear();

                _state = StateConnected;
            }

            Debug.Assert(_state == StateConnected);
            return SocketOperation.None;
        }
Ejemplo n.º 21
0
 private void server_ErrorReceived(object sender, NetSockErrorReceivedEventArgs e)
 {
     if (e.Exception.GetType() == typeof(System.Net.Sockets.SocketException))
     {
         System.Net.Sockets.SocketException s = (System.Net.Sockets.SocketException)e.Exception;
         account.Log(new ErrorTextInformation("Error: " + e.Function + " - " + s.SocketErrorCode.ToString() + "\r\n" + s.ToString()), 0);
     }
     else
     {
         account.Log(new ErrorTextInformation("Error: " + e.Function + "\r\n" + e.Exception.ToString()), 0);
     }
 }
Ejemplo n.º 22
0
 private void OnSocketError(object sender, EventNetSockErrorReceived e)
 {
     if (e.Exception.GetType() == typeof(System.Net.Sockets.SocketException))
     {
         System.Net.Sockets.SocketException s = (System.Net.Sockets.SocketException)e.Exception;
         Debug.Log("OnSocketError > System.Net.Sockets Exception " + e.Function + " - " + s.SocketErrorCode.ToString() + " => " + s.ToString());
     }
     else
     {
         Debug.Log("OnSocketError > ERROR : " + e.Function.ToString() + " => " + e.Exception.ToString());
     }
     _ReceiveSchedule.AddMessage(eEventIDs.SocketError);
 }
Ejemplo n.º 23
0
 private void catchSocketException(System.Net.Sockets.SocketException e)
 {
     Console.WriteLine("Socket Error...");
     if (e.ErrorCode == /*WSAECONNRESET*/ 0x2746)
     {
         state = CONNSTATE.Disconnected;
         form.updateConnectionListEntry(this);
     }
     else
     {
         die();
     }
 }
Ejemplo n.º 24
0
        public static void ThrowServerException(SocketException e, ServerContext serverContext = null)
        {
            string ipAddress = serverContext != null ? serverContext.IPAddress.ToString() : "unknown";
            string port = serverContext != null ? serverContext.Port.ToString() : "-";

            if (ipAddress.Equals("0.0.0.0")) ipAddress = "any";

            if (e.Message.StartsWith("Only one usage of each socket address"))
                throw new ServerException(
                    string.Format(
                        "Can't bind to socket on port {0} for IP addresses ({1}) because it is already in use (is the server already running?)",
                        port, ipAddress), e);

            throw e;
        }
Ejemplo n.º 25
0
        void WriteCallback(IAsyncResult ar)
        {
            try
            {
                RemoteHostState state = ar.AsyncState as RemoteHostState;
                state.Stream.EndWrite(ar);
            }
            catch (System.IO.IOException ioe)
            {
                if (ioe.InnerException.GetType() == typeof(System.Net.Sockets.SocketError))
                {
                    System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ioe.InnerException;
                    if (DoCloseConnection())
                    {
                        OnClosedConnection((se.SocketErrorCode == SocketError.Interrupted) ? null : se);
                    }
                }
                else
                if (DoCloseConnection())
                {
                    OnClosedConnection(ioe);
                }

                return;
            }
            //We dont need to take care of ObjectDisposedException.
            //ObjectDisposedException would indicate that the state has been closed, and that means it has been disconnected already
            catch { }

            bool doSendMore = false;

            if (RemoteState != null)
            {
                lock (RemoteState.SendQueue)
                {
                    RemoteState.SendQueue.Dequeue();
                    if (RemoteState.SendQueue.Count > 0)
                    {
                        doSendMore = true;
                    }
                }
            }

            if (doSendMore)
            {
                DoSend();
            }
        }
Ejemplo n.º 26
0
 public static bool IsDisconnected(SocketException exception)
 {
     switch ((SocketError) exception.ErrorCode)
     {
         case SocketError.ConnectionAborted:
         case SocketError.ConnectionReset:
         case SocketError.Fault:
         case SocketError.NetworkReset:
         case SocketError.OperationAborted:
         case SocketError.Shutdown:
         case SocketError.SocketError:
         case SocketError.TimedOut:
             return true;
     }
     return false;
 }
Ejemplo n.º 27
0
 public static bool IsSocketDisconnectedException(SocketException socketException)
 {
     var errorCode = socketException.SocketErrorCode;
     return errorCode == SocketError.NetworkDown ||
            errorCode == SocketError.NetworkReset ||
            errorCode == SocketError.NetworkUnreachable ||
            errorCode == SocketError.ConnectionAborted ||
            errorCode == SocketError.ConnectionReset ||
            errorCode == SocketError.HostNotFound ||
            errorCode == SocketError.HostUnreachable ||
            errorCode == SocketError.NotConnected ||
            errorCode == SocketError.Shutdown ||
            errorCode == SocketError.Disconnecting ||
            errorCode == SocketError.AddressNotAvailable ||
            errorCode == SocketError.TimedOut;
 }
Ejemplo n.º 28
0
        protected bool ValidateAsyncResult(SocketAsyncEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            if (e.SocketError != SocketError.Success)
            {
                var socketException = new SocketException((int)e.SocketError);
                this.OnCompleted(new ProxyEventArgs(new Exception(socketException.Message, socketException)));
                return false;
            }

            return true;
        }
Ejemplo n.º 29
0
        private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        {
            if (ExceptionLogger != null)
            {
                System.Net.Sockets.SocketException tempExcption = null;
                if (e.Exception is System.Net.Sockets.SocketException)
                {
                    tempExcption = (System.Net.Sockets.SocketException)e.Exception;
                }

                if (tempExcption == null || (tempExcption.ErrorCode != 125 && tempExcption.ErrorCode != 111 && tempExcption.ErrorCode != 104))
                {
                    ExceptionLogger.Error("Exception: {0} ", e.Exception.ToString());
                }
            }
        }
Ejemplo n.º 30
0
        void Complete(SocketAsyncEventArgs e, bool completeSynchronously)
        {
            TransportBase transport = null;
            Exception exception = null;
            if (e.SocketError != SocketError.Success)
            {
                exception = new SocketException((int)e.SocketError);
                if (e.AcceptSocket != null)
                {
                    e.AcceptSocket.Dispose();
                }
            }
            else
            {
                try
                {
                    Fx.Assert(e.ConnectSocket != null, "Must have a valid socket accepted.");
                    e.ConnectSocket.NoDelay = true;
                    transport = new TcpTransport(e.ConnectSocket, this.transportSettings);
                    transport.Open();
                }
                catch (Exception exp)
                {
                    if (Fx.IsFatal(exp))
                    {
                        throw;
                    }

                    exception = exp;
                    if (transport != null)
                    {
                        transport.SafeClose();
                    }
                    transport = null;
                }
            }

            e.Dispose();
            this.callbackArgs.CompletedSynchronously = completeSynchronously;
            this.callbackArgs.Exception = exception;
            this.callbackArgs.Transport = transport;

            if (!completeSynchronously)
            {
                this.callbackArgs.CompletedCallback(this.callbackArgs);
            }
        }
Ejemplo n.º 31
0
        public static void Connect(this TcpClient connection, string ip, int port, out SocketException ex)
        {
            ex = null;

            for (int i = 0; i < 10 && !connection.Connected; i++)
            {
                try
                {
                    connection.Connect(IPAddress.Parse(ip), port);
                    break;
                }
                catch (SocketException se)
                {
                    ex = se;
                    continue;
                }
            }
        }
Ejemplo n.º 32
0
        private static void ShowError(SocketException aSocketException)
        {
            String errorText;
            switch (aSocketException.ErrorCode)
            {
                case 10060:
                    errorText = ExceptionStrings.ErrorWsaETimedOut;
                    break;
                case 10061:
                    errorText = ExceptionStrings.ErrorWsaEConnRefused;
                    break;
                default:
                    errorText = Convert.ToString(aSocketException.ErrorCode) + "; " + aSocketException.Message;
                    break;
            }

            ShowError(errorText);
        }
Ejemplo n.º 33
0
 internal static Exception ConvertSocketException(SocketException socketException, string operation)
 {
     if (socketException.ErrorCode == 10049 // WSAEADDRNOTAVAIL 
         || socketException.ErrorCode == 10061 // WSAECONNREFUSED 
         || socketException.ErrorCode == 10050 // WSAENETDOWN 
         || socketException.ErrorCode == 10051 // WSAENETUNREACH 
         || socketException.ErrorCode == 10064 // WSAEHOSTDOWN 
         || socketException.ErrorCode == 10065) // WSAEHOSTUNREACH
     {
         return new EndpointNotFoundException(string.Format(operation + " error: {0} ({1})", socketException.Message, socketException.ErrorCode), socketException);
     }
     if (socketException.ErrorCode == 10060) // WSAETIMEDOUT
     {
         return new TimeoutException(operation + " timed out.", socketException);
     }
     else
     {
         return new CommunicationException(string.Format(operation + " error: {0} ({1})", socketException.Message, socketException.ErrorCode), socketException);
     }
 }
Ejemplo n.º 34
0
        private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            CheckTransmitFileOptions(flags);

            // Open the file, if any
            // Open it before we send the preBuffer so that any exception happens first
            FileStream fileStream = OpenFile(fileName);

            SocketError errorCode = SocketError.Success;
            using (fileStream)
            {
                // Send the preBuffer, if any
                // This will throw on error
                if (preBuffer != null && preBuffer.Length > 0)
                {
                    Send(preBuffer);
                }

                // Send the file, if any
                if (fileStream != null)
                {
                    // This can throw ObjectDisposedException.
                    errorCode = SocketPal.SendFile(_handle, fileStream);
                }
            }

            if (errorCode != SocketError.Success)
            {
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException);
                throw socketException;
            }

            // Send the postBuffer, if any
            // This will throw on error
            if (postBuffer != null && postBuffer.Length > 0)
            {
                Send(postBuffer);
            }
        }
Ejemplo n.º 35
0
        public void Connect(TcpClient client, out SocketException ex)
        {
            ex = null;

            for (int i = 0; i < 10 && !ReadWriteClient.Connected; i++)
            {
                try
                {
                    if (client.Equals(ReadWriteClient))
                        client.Connect(_readWriteEndpoint);
                    if (client.Equals(ReadOnlyClient))
                        client.Connect(_readOnlyEndpoint);
                    break;
                }
                catch (SocketException se)
                {
                    ex = se;
                    continue;
                }
            }
        }
Ejemplo n.º 36
0
        void DoSend()
        {
            try
            {
                byte[] data = null;
                lock (RemoteState.SendQueue)
                {
                    if (RemoteState.SendQueue.Count > 0)
                    {
                        data = RemoteState.SendQueue.Peek();
                    }
                }

                if (data != null)
                {
                    RemoteState.Stream.BeginWrite(data, 0, data.Length, writeCallback, RemoteState);
                }
            }
            catch (System.IO.IOException ioe)
            {
                if (ioe.InnerException.GetType() == typeof(System.Net.Sockets.SocketError))
                {
                    System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ioe.InnerException;
                    if (DoCloseConnection())
                    {
                        OnClosedConnection((se.SocketErrorCode == SocketError.Interrupted) ? null : se);
                    }
                }
                else
                if (DoCloseConnection())
                {
                    OnClosedConnection(ioe);
                }
            }
            //We dont need to take care of ObjectDisposedException.
            //ObjectDisposedException would indicate that the state has been closed, and that means it has been disconnected already
            catch { }
        }
Ejemplo n.º 37
0
        private static void CallBackMethod(IAsyncResult asyncresult)
        {
            try
            {
                IsConnectionSuccessful = false;
                TcpClient tcpclient = asyncresult.AsyncState as TcpClient;

                if (tcpclient.Client != null)
                {
                    tcpclient.EndConnect(asyncresult);
                    IsConnectionSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                IsConnectionSuccessful = false;
                socketexception = (SocketException) ex;
            }
            finally
            {
                TimeoutObject.Set();
            }
        }
Ejemplo n.º 38
0
 /// <summary>
 /// 错误日志
 /// </summary>
 /// <param name="error">错误异常</param>
 public static void ErrorLog(Exception error)
 {
     if (error != null)
     {
         IOException ioError = error as IOException;
         if (ioError != null)
         {
             error = ioError.InnerException;
         }
         ObjectDisposedException disposedError = error.InnerException as ObjectDisposedException;
         if (disposedError == null)
         {
             System.Net.Sockets.SocketException socketException = error as System.Net.Sockets.SocketException;
             if (socketException == null || socketException.ErrorCode != 10053 || socketException.ErrorCode != 10054)
             {
                 log.Default.Add(error, null, true);
             }
         }
         else
         {
             log.Default.Add(error, null, true);
         }
     }
 }
        public void SplashPresenter_StartApplication_Picks_Up_SocketExceptions_When_Starting_WebServer()
        {
            var exception = new SocketException();
            _WebServer.SetupSet(s => s.Online = true).Callback(() => {
                throw exception;
            });
            _WebServer.Setup(a => a.Port).Returns(123);

            _Presenter.Initialise(_View.Object);
            _Presenter.StartApplication();

            _Log.Verify(g => g.WriteLine("Caught exception when starting web server: {0}", exception.ToString()), Times.Once());
            _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotStartWebServerFull, 123), Strings.CannotStartWebServerTitle, false), Times.Once());
            _View.Verify(v => v.ReportProblem(Strings.SuggestUseDifferentPortFull, Strings.SuggestUseDifferentPortTitle, false), Times.Once());
        }
Ejemplo n.º 40
0
        // Callback which fires when an internal connection attempt completes.
        // If it failed and there are more addresses to try, do it.
        private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
        {
            Exception exception = null;

            lock (_lockObject)
            {
                if (_state == State.Canceled)
                {
                    // If Cancel was called before we got the lock, the Socket will be closed soon.  We need to report
                    // OperationAborted (even though the connection actually completed), or the user will try to use a
                    // closed Socket.
                    exception = new SocketException((int)SocketError.OperationAborted);
                }
                else if (_state == State.ConnectAttempt)
                {
                    if (args.SocketError == SocketError.Success)
                    {
                        if (RequiresUserConnectAttempt)
                        {
                            exception = AttemptUserConnection();

                            if (exception == null)
                            {
                                // Don't call the callback; we've started a connection attempt on the
                                // user's socket.
                                _state = State.UserConnectAttempt;
                                return;
                            }
                        }

                        // The connection attempt succeeded or the user connect attempt failed synchronously; go to the
                        // completed state. The callback will be called outside the lock.
                        _state = State.Completed;
                    }
                    else if (args.SocketError == SocketError.OperationAborted)
                    {
                        // The socket was closed while the connect was in progress.  This can happen if the user
                        // closes the socket, and is equivalent to a call to CancelConnectAsync
                        exception = new SocketException((int)SocketError.OperationAborted);
                        _state    = State.Canceled;
                    }
                    else
                    {
                        // Try again, if there are more IPAddresses to be had.

                        // If the underlying OS does not support multiple connect attempts
                        // on the same socket, dispose the socket used for the last attempt.
                        if (!SocketPal.SupportsMultipleConnectAttempts)
                        {
                            _lastAttemptSocket.Dispose();
                        }

                        // Keep track of this because it will be overwritten by AttemptConnection
                        SocketError currentFailure   = args.SocketError;
                        Exception   connectException = AttemptConnection();

                        if (connectException == null)
                        {
                            // don't call the callback, another connection attempt is successfully started
                            return;
                        }
                        else
                        {
                            SocketException socketException = connectException as SocketException;
                            if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
                            {
                                // If the error is NoData, that means there are no more IPAddresses to attempt
                                // a connection to.  Return the last error from an actual connection instead.
                                exception = new SocketException((int)currentFailure);
                            }
                            else
                            {
                                exception = connectException;
                            }

                            _state = State.Completed;
                        }
                    }
                }
                else
                {
                    if (GlobalLog.IsEnabled)
                    {
                        if (_state != State.UserConnectAttempt)
                        {
                            GlobalLog.Assert("MultipleConnectAsync.InternalConnectCallback(): Unexpected object state");
                        }
                        if (!RequiresUserConnectAttempt)
                        {
                            GlobalLog.Assert("MultipleConnectAsync.InternalConnectCallback(): State.UserConnectAttempt without RequiresUserConnectAttempt");
                        }
                    }

                    if (args.SocketError == SocketError.Success)
                    {
                        _state = State.Completed;
                    }
                    else if (args.SocketError == SocketError.OperationAborted)
                    {
                        // The socket was closed while the connect was in progress.  This can happen if the user
                        // closes the socket, and is equivalent to a call to CancelConnectAsync
                        exception = new SocketException((int)SocketError.OperationAborted);
                        _state    = State.Canceled;
                    }
                    else
                    {
                        // The connect attempt on the user's socket failed. Return the corresponding error.
                        exception = new SocketException((int)args.SocketError);
                        _state    = State.Completed;
                    }
                }
            }

            if (exception == null)
            {
                Succeed();
            }
            else
            {
                AsyncFail(exception);
            }
        }
Ejemplo n.º 41
0
        // Callback which fires when an internal connection attempt completes.
        // If it failed and there are more addresses to try, do it.
        private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
        {
            Exception exception = null;

            lock (_lockObject)
            {
                if (_state == State.Canceled)
                {
                    // If Cancel was called before we got the lock, the Socket will be closed soon.  We need to report
                    // OperationAborted (even though the connection actually completed), or the user will try to use a
                    // closed Socket.
                    exception = new SocketException((int)SocketError.OperationAborted);
                }
                else
                {
                    Debug.Assert(_state == State.ConnectAttempt);

                    if (args.SocketError == SocketError.Success)
                    {
                        // The connection attempt succeeded; go to the completed state.
                        // The callback will be called outside the lock.
                        _state = State.Completed;
                    }
                    else if (args.SocketError == SocketError.OperationAborted)
                    {
                        // The socket was closed while the connect was in progress.  This can happen if the user
                        // closes the socket, and is equivalent to a call to CancelConnectAsync
                        exception = new SocketException((int)SocketError.OperationAborted);
                        _state    = State.Canceled;
                    }
                    else
                    {
                        // Keep track of this because it will be overwritten by AttemptConnection
                        SocketError currentFailure   = args.SocketError;
                        Exception   connectException = AttemptConnection();

                        if (connectException == null)
                        {
                            // don't call the callback, another connection attempt is successfully started
                            return;
                        }
                        else
                        {
                            SocketException socketException = connectException as SocketException;
                            if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
                            {
                                // If the error is NoData, that means there are no more IPAddresses to attempt
                                // a connection to.  Return the last error from an actual connection instead.
                                exception = new SocketException((int)currentFailure);
                            }
                            else
                            {
                                exception = connectException;
                            }

                            _state = State.Completed;
                        }
                    }
                }
            }

            if (exception == null)
            {
                Succeed();
            }
            else
            {
                AsyncFail(exception);
            }
        }
Ejemplo n.º 42
0
 private static IOException GetExceptionFromSocketException(string message, SocketException innerException)
 {
     return(new IOException(message, innerException));
 }
Ejemplo n.º 43
0
        // Callback which fires when an internal connection attempt completes.
        // If it failed and there are more addresses to try, do it.
        // Returns true if the operation is pending, false if it completed synchronously.
        private bool DoConnectCallback(SocketAsyncEventArgs args, bool sync)
        {
            Exception?exception = null;

            Debug.Assert(!Monitor.IsEntered(_lockObject));
            lock (_lockObject)
            {
                if (_state == State.Canceled)
                {
                    // If Cancel was called before we got the lock, the Socket will be closed soon.  We need to report
                    // OperationAborted (even though the connection actually completed), or the user will try to use a
                    // closed Socket.
                    exception = new SocketException((int)SocketError.OperationAborted);
                }
                else
                {
                    while (true)
                    {
                        Debug.Assert(_state == State.ConnectAttempt);

                        if (args.SocketError == SocketError.Success)
                        {
                            // The connection attempt succeeded; go to the completed state.
                            // The callback will be called outside the lock.
                            _state = State.Completed;
                            break;
                        }
                        else if (args.SocketError == SocketError.OperationAborted)
                        {
                            // The socket was closed while the connect was in progress.  This can happen if the user
                            // closes the socket, and is equivalent to a call to CancelConnectAsync
                            exception = new SocketException((int)SocketError.OperationAborted);
                            _state    = State.Canceled;
                            break;
                        }
                        else
                        {
                            // Keep track of this because it will be overwritten by AttemptConnection
                            SocketError currentFailure = args.SocketError;

                            (Exception? connectException, bool pending) = AttemptConnection();

                            if (connectException == null)
                            {
                                if (pending)
                                {
                                    // don't call the callback, another connection attempt is successfully started
                                    return(true);
                                }

                                // We have a sync completion from AttemptConnection.
                                // Loop around and process its results.
                            }
                            else
                            {
                                SocketException?socketException = connectException as SocketException;
                                if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
                                {
                                    // If the error is NoData, that means there are no more IPAddresses to attempt
                                    // a connection to.  Return the last error from an actual connection instead.
                                    exception = new SocketException((int)currentFailure);
                                }
                                else
                                {
                                    exception = connectException;
                                }

                                _state = State.Completed;
                                break;
                            }
                        }
                    }
                }
            }

            if (exception != null)
            {
                return(Fail(sync, exception));
            }
            else
            {
                return(Succeed(sync));
            }
        }
Ejemplo n.º 44
0
            private void ThrowIOSocketException()
            {
                var se = new SocketException((int)SocketError);

                throw new IOException(SR.Format(SR.net_io_readfailure, se.Message), se);
            }
Ejemplo n.º 45
0
 /// <summary>
 /// Raises the <see cref="ClientBase.ReceiveDataException"/> event.
 /// </summary>
 /// <param name="ex">Exception to send to <see cref="ClientBase.ReceiveDataException"/> event.</param>
 protected void OnReceiveDataException(SocketException ex)
 {
     if (ex.SocketErrorCode != SocketError.Disconnecting)
         OnReceiveDataException((Exception)ex);
 }
Ejemplo n.º 46
0
        private void ReadCallback(IAsyncResult ar)
        {
            try
            {
                RemoteHostState state = ar.AsyncState as RemoteHostState;
                int             len   = 0;
                len = state.Stream.EndRead(ar);

                if (len == 0)
                {
                    CloseConnection();
                }
                else
                {
                    try
                    {
                        if (ProtocolStrategy != null)
                        {
                            if (ProtocolStrategy.Encoding != null)
                            {
                                if (state.Decoder == null)
                                {
                                    state.Decoder = ProtocolStrategy.Encoding.GetDecoder();
                                }

                                int    charCount = state.Decoder.GetCharCount(state.ReadBuffer, 0, len);
                                char[] chars     = new char[charCount];
                                state.Decoder.GetChars(state.ReadBuffer, 0, len, chars, 0);
                                string msg = new string(chars);

                                ProtocolStrategy.Parse(msg, state);
                            }
                            else
                            {
                                ProtocolStrategy.Parse(state.ReadBuffer, len, state);
                            }
                        }
                    }
                    catch { }

                    state.Stream.BeginRead(state.ReadBuffer, 0, state.ReadBuffer.Length, readCallback, state);
                }
            }
            catch (System.IO.IOException ioe)
            {
                if (ioe.InnerException.GetType() == typeof(System.Net.Sockets.SocketError))
                {
                    System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ioe.InnerException;

                    if (DoCloseConnection())
                    {
                        OnClosedConnection((se.SocketErrorCode == SocketError.Interrupted) ? null : se);
                    }
                }
                else
                if (DoCloseConnection())
                {
                    OnClosedConnection(ioe);
                }
            }
            //We dont need to take care of ObjectDisposedException.
            //ObjectDisposedException would indicate that the state has been closed, and that means it has been disconnected already
            catch { }
        }
Ejemplo n.º 47
0
        private async Task <SocketMessage> InternalReceiveAsync()
        {
            if (this.Closed)
            {
                throw new SocketException((int)SocketError.NotConnected);
            }

            SocketMessage msg = null;

            try
            {
                using (BinaryReader streamReader = new BinaryReader(this.Stream, Encoding.UTF8, true))
                {
                    int    len   = streamReader.ReadInt32();
                    byte[] block = streamReader.ReadBytes(len);

                    object result = null;
                    if (len != block.Length)
                    {
                        // Can happen if the process at the other side of this socket was terminated.
                        // If we don't have the exact requested bytes then we cannot deserialize it.
                    }
                    else
                    {
                        try
                        {
                            result = this.Serializer.ReadObject(new MemoryStream(block));
                        }
                        catch (Exception)
                        {
                            // This can also happen when process on other side is terminated, the last network
                            // packet can be scrambled.  This is usually just the DisconnectMessageId which is
                            // ignorable.
                        }
                    }

                    var wrapper = result as MessageWrapper;
                    if (wrapper != null && wrapper.Message is SocketMessage)
                    {
                        msg = (SocketMessage)wrapper.Message;
                        if (msg.Id == DisconnectMessageId)
                        {
                            // client is politely saying good bye...
                            this.OnClosed();
                        }
                        else if (msg.Id == ConnectedMessageId)
                        {
                            // must send an acknowledgement of the connect message
                            this.Name = msg.Sender;
                            await this.SendAsync(new SocketMessage(MessageAck, this.Name));
                        }
                        else if (msg.Id == OpenBackChannelMessageId && this.Server != null)
                        {
                            // client is requesting a back channel.
                            await this.HandleBackchannelRequest(msg);
                        }
                    }
                }
            }
            catch (EndOfStreamException)
            {
                this.OnClosed();
            }
            catch (System.IO.IOException ioe)
            {
                System.Net.Sockets.SocketException se = ioe.InnerException as System.Net.Sockets.SocketException;
                if (se.SocketErrorCode == SocketError.ConnectionReset)
                {
                    this.OnClosed();
                }
            }
            catch (Exception ex)
            {
                this.OnError(ex);
            }

            return(msg);
        }
Ejemplo n.º 48
0
 internal void OnSocketError(SocketException socketException)
 {
     _completionSource.TrySetException(new JdwpException(ErrorCode.SocketError, "Socket error reading the result", socketException));
 }
Ejemplo n.º 49
0
        public void FinishWrite(IList <ArraySegment <byte> > buffer, ref int offset)
        {
            Debug.Assert(_writeEventArgs != null);
            Debug.Assert(offset == 0);
            if (_fd == null)
            {
                int count = buffer.GetByteCount(); // Assume all the data was sent for at-most-once semantics.
                _writeEventArgs = null;
                offset          = count;
                return;
            }

            if (!_incoming && _state < StateConnected)
            {
                if (_writeEventArgs.SocketError != SocketError.Success)
                {
                    var ex = new System.Net.Sockets.SocketException((int)_writeEventArgs.SocketError);
                    if (Network.ConnectionRefused(ex))
                    {
                        throw new ConnectionRefusedException(ex);
                    }
                    else
                    {
                        throw new ConnectFailedException(ex);
                    }
                }
                return;
            }

            int ret;

            try
            {
                if (_writeEventArgs.SocketError != SocketError.Success)
                {
                    throw new System.Net.Sockets.SocketException((int)_writeEventArgs.SocketError);
                }
                ret = _writeEventArgs.BytesTransferred;
                _writeEventArgs.SetBuffer(null, 0, 0);
                if (_writeEventArgs.BufferList != null && _writeEventArgs.BufferList != buffer)
                {
                    _writeEventArgs.BufferList.Clear();
                }
                _writeEventArgs.BufferList = null;
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                if (Network.ConnectionLost(ex))
                {
                    throw new ConnectionLostException(ex);
                }
                else
                {
                    throw new Ice.SocketException(ex);
                }
            }

            if (ret == 0)
            {
                throw new ConnectionLostException();
            }

            Debug.Assert(ret > 0);
            Debug.Assert(ret == buffer.GetByteCount());
            offset = ret;
            return;
        }
Ejemplo n.º 50
0
 private void _DaemonPipe_OnDisconnected(SocketException se)
 {
     if (se != null) Console.WriteLine("Disconnected! " + se.Message);
     else Console.WriteLine("Disconnected!");
 }
Ejemplo n.º 51
0
        private async Task SendFileInternalAsync(FileStream fileStream, byte[] preBuffer, byte[] postBuffer)
        {
            SocketError errorCode = SocketError.Success;

            using (fileStream)
            {
                // Send the preBuffer, if any
                // This will throw on error
                if (preBuffer != null && preBuffer.Length > 0)
                {
                    // Using "this." makes the extension method kick in
                    await this.SendAsync(new ArraySegment <byte>(preBuffer), SocketFlags.None).ConfigureAwait(false);
                }

                // Send the file, if any
                if (fileStream != null)
                {
                    var tcs = new TaskCompletionSource <bool>();

                    // This can throw ObjectDisposedException.
                    errorCode = SocketPal.SendFileAsync(_handle, fileStream, (bytesTransferred, socketError) =>
                    {
                        if (socketError != SocketError.Success)
                        {
                            // Synchronous exception from SendFileAsync
                            SocketException socketException = new SocketException((int)errorCode);
                            UpdateStatusAfterSocketError(socketException);
                            if (NetEventSource.IsEnabled)
                            {
                                NetEventSource.Error(this, socketException);
                            }
                            tcs.SetException(socketException);
                        }

                        tcs.SetResult(true);
                    });

                    await tcs.Task.ConfigureAwait(false);
                }
            }

            if (errorCode != SocketError.Success)
            {
                // Synchronous exception from SendFileAsync
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(this, socketException);
                }
                throw socketException;
            }

            // Send the postBuffer, if any
            // This will throw on error
            if (postBuffer != null && postBuffer.Length > 0)
            {
                // Using "this." makes the extension method kick in
                await this.SendAsync(new ArraySegment <byte>(postBuffer), SocketFlags.None).ConfigureAwait(false);
            }
        }