public unsafe void ReceiveChunk(string endpoint, bool isAlive, int bytesReceived, SocketError status)
		{
			if (IsEnabled())
			{
				fixed (char* pEndpoint = endpoint)
				{
					var data = stackalloc EventData[4];

					data[0].DataPointer = (IntPtr)(pEndpoint);
					data[0].Size = (endpoint.Length + 1) * 2;

					var alive = isAlive ? 1 : 0;
					data[1].DataPointer = (IntPtr)(&alive);
					data[1].Size = sizeof(int);

					data[2].DataPointer = (IntPtr)(&bytesReceived);
					data[2].Size = sizeof(int);

					data[3].Size = sizeof(int);
					data[3].DataPointer = (IntPtr)(&status);

					WriteEventCore(22, 4, data);
				}
			}
		}
 private void OnClientDisconnect(ServerClient arg1, SocketError arg2)
 {
     Console.WriteLine("Disconnected");
     _timeSyncCompleted = false;
     _completedEvent.Set();
     _batchCounter = 0;
 }
        /// <summary>
        /// Connect TCP socket to a server.
        /// </summary>
        /// <param name="serverAddr">IP or hostname of server.</param>
        /// <param name="port">Port that TCP should use.</param>
        /// <returns>True if connection is successful otherwise false</returns>
        internal bool Connect(string serverAddr, int port)
        {
            try
            {
                IPAddress[] serverIP = Dns.GetHostAddresses(serverAddr);
                if (serverIP.Length <= 0)
                {
                    mErrorString = "Error looking up host name";
                    return false;
                }

                mTCPClient = new TcpClient();
                mTCPClient.Connect(serverIP[0], port);
                // Disable Nagle's algorithm
                mTCPClient.NoDelay = true;
            }
            catch (SocketException e)
            {
                mErrorString = e.Message;
                mErrorCode = e.SocketErrorCode;

                if (mTCPClient != null)
                {
                    mTCPClient.Close();
                }

                return false;
            }

            return true;
        }
 private void InitOption(MailStatus status, MailCause cause)
 {
     this.mStatus = status;
     this.mCause = cause;
     this.mSocketErrorCode = 0;
     this.mSocketErrorCodeType = SocketError.Success;
 }
Exemple #5
0
        public void InCompleted(SocketError socketError, int bytesTransferred)
        {
            if (socketError != SocketError.Success)
            {
                m_socket.EventAcceptFailed(m_address.ToString(), ErrorHelper.SocketErrorToErrorCode(socketError));

                // dispose old object
                m_acceptedSocket.Handle.Dispose();

                Accept();
            }
            else
            {
                m_acceptedSocket.InitOptions();

                var pgmSession = new PgmSession(m_acceptedSocket, m_options);

                IOThread ioThread = ChooseIOThread(m_options.Affinity);

                SessionBase session = SessionBase.Create(ioThread, false, m_socket, m_options, new Address(m_handle.LocalEndPoint));

                session.IncSeqnum();
                LaunchChild(session);
                SendAttach(session, pgmSession, false);
                m_socket.EventAccepted(m_address.ToString(), m_acceptedSocket.Handle);

                Accept();
            }
        }
 private void OnConnectionFailed(ITcpConnection connection, SocketError socketError)
 {
     if (Interlocked.CompareExchange(ref _isClosed, 1, 0) == 0)
     {
         Console.WriteLine("Connection '{0}' ({1:B}) to [{2}] failed: {3}.", _connectionName, _connectionId, connection.RemoteEndPoint, socketError);
     }
 }
 internal SocketError CheckAsyncCallOverlappedResult(SocketError errorCode)
 {
     if (this.m_UseOverlappedIO)
     {
         switch (errorCode)
         {
             case SocketError.Success:
             case SocketError.IOPending:
                 ThreadPool.UnsafeRegisterWaitForSingleObject(this.m_OverlappedEvent, new WaitOrTimerCallback(this.OverlappedCallback), this, -1, true);
                 return SocketError.Success;
         }
         base.ErrorCode = (int) errorCode;
         base.Result = -1;
         this.ReleaseUnmanagedStructures();
         return errorCode;
     }
     this.ReleaseUnmanagedStructures();
     switch (errorCode)
     {
         case SocketError.Success:
         case SocketError.IOPending:
             return SocketError.Success;
     }
     base.ErrorCode = (int) errorCode;
     base.Result = -1;
     if (this.m_Cache != null)
     {
         this.m_Cache.Overlapped.AsyncResult = null;
     }
     this.ReleaseUnmanagedStructures();
     return errorCode;
 }
 private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     if (Interlocked.CompareExchange(ref _isClosed, 1, 0) == 0)
     {
         Console.WriteLine("Connection '{0}' [{1:B}] closed: {2}.", connection.ConnectionId, connection.RemoteEndPoint, socketError);
     }
 }
        private void AcceptCompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError)
        {
            _acceptedFileDescriptor = acceptedFileDescriptor;
            Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer, $"Unexpected socketAddress: {socketAddress}");
            _acceptAddressBufferCount = socketAddressSize;

            CompletionCallback(0, socketError);
        }
        private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
        {
            connection.ConnectionClosed -= OnConnectionClosed;

            var handler = ConnectionClosed;
            if (handler != null)
                handler(this, socketError);
        }
Exemple #11
0
 internal CompletionStatus(AsyncSocket asyncSocket, object state, OperationType operationType, SocketError socketError, int bytesTransferred) : 
     this()
 {
     AsyncSocket = asyncSocket;
     State = state;
     OperationType = operationType;
     SocketError = socketError;
     BytesTransferred = bytesTransferred;
 }
 public override bool Close () {
     try {
         socket.Close();
         return true;
     } catch (SocketException exn) {
         socketError = exn.SocketErrorCode;
         return false;
     }
 }
Exemple #13
0
        /// <summary>Creates a new instance of the <see cref='System.Net.Sockets.SocketException'/> class with the specified error code as SocketError.</summary>
        internal SocketException(SocketError socketError) : base(GetNativeErrorForSocketError(socketError))
        {
            _errorCode = socketError;

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print($"SocketException::.ctor(SocketError={socketError}):{Message}");
            }
        }
        internal SocketException(SocketError errorCode, uint platformError) : base((int)platformError)
        {
            _errorCode = errorCode;

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print($"SocketException::.ctor(SocketError={errorCode}, uint={platformError}):{Message}");
            }
        }
        public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError errorCode)
        {
            if (_socketAddress != null)
            {
                Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);
                _socketAddressSize = socketAddressSize;
            }

            base.CompletionCallback(numBytes, errorCode);
        }
        private void AcceptCompletionCallback(int acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError)
        {
            // TODO: receive bytes on socket if requested

            _acceptedFileDescriptor = acceptedFileDescriptor;
            Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer);
            _acceptAddressBufferCount = socketAddressSize;

            CompletionCallback(0, socketError);
        }
        public static string GetDesc(SocketError e)
        {
            switch(e)
            {
                case SocketError.Success: return "The Socket operation succeeded.";
                case SocketError.SocketError: return "An unspecified Socket error has occurred.";
                case SocketError.Interrupted: return "A blocking Socket call was canceled.";
                case SocketError.AccessDenied: return "An attempt was made to access a Socket in a way that is forbidden by its access permissions.";
                case SocketError.Fault: return "An invalid pointer address was detected by the underlying socket provider.";
                case SocketError.InvalidArgument: return "An invalid argument was supplied to a Socket member.";
                case SocketError.TooManyOpenSockets: return "There are too many open sockets in the underlying socket provider.";
                case SocketError.WouldBlock: return "An operation on a nonblocking socket cannot be completed immediately.";
                case SocketError.InProgress: return "A blocking operation is in progress.";
                case SocketError.AlreadyInProgress: return "The nonblocking Socket already has an operation in progress.";
                case SocketError.NotSocket: return "A Socket operation was attempted on a non-socket.";
                case SocketError.DestinationAddressRequired: return "A required address was omitted from an operation on a Socket.";
                case SocketError.MessageSize: return "The datagram is too long.";
                case SocketError.ProtocolType: return "The protocol type is incorrect for this Socket.";
                case SocketError.ProtocolOption: return "An unknown, invalid, or unsupported option or level was used with a Socket.";
                case SocketError.ProtocolNotSupported: return "The protocol is not implemented or has not been configured.";
                case SocketError.SocketNotSupported: return "The support for the specified socket type does not exist in this address family.";
                case SocketError.OperationNotSupported: return "The address family is not supported by the protocol family.";
                case SocketError.ProtocolFamilyNotSupported: return "The protocol family is not implemented or has not been configured.";
                case SocketError.AddressFamilyNotSupported: return "The address family specified is not supported. This error is returned if the IPv6 address family was specified and the IPv6 stack is not installed on the local machine. This error is returned if the IPv4 address family was specified and the IPv4 stack is not installed on the local machine.";
                case SocketError.AddressAlreadyInUse: return "Only one use of an address is normally permitted.";
                case SocketError.AddressNotAvailable: return "The selected IP address is not valid in this context.";
                case SocketError.NetworkDown: return "The network is not available.";
                case SocketError.NetworkUnreachable: return "No route to the remote host exists.";
                case SocketError.NetworkReset: return "The application tried to set KeepAlive on a connection that has already timed out.";
                case SocketError.ConnectionAborted: return "The connection was aborted by the .NET Framework or the underlying socket provider.";
                case SocketError.ConnectionReset: return "The connection was reset by the remote peer.";
                case SocketError.NoBufferSpaceAvailable: return "No free buffer space is available for a Socket operation.";
                case SocketError.IsConnected: return "The Socket is already connected.";
                case SocketError.NotConnected: return "The application tried to send or receive data, and the Socket is not connected.";
                case SocketError.Shutdown: return "A request to send or receive data was disallowed because the Socket has already been closed.";
                case SocketError.TimedOut: return "The connection attempt timed out, or the connected host has failed to respond.";
                case SocketError.ConnectionRefused: return "The remote host is actively refusing a connection.";
                case SocketError.HostDown: return "The operation failed because the remote host is down.";
                case SocketError.HostUnreachable: return "There is no network route to the specified host.";
                case SocketError.ProcessLimit: return "Too many processes are using the underlying socket provider.";
                case SocketError.SystemNotReady: return "The network subsystem is unavailable.";
                case SocketError.VersionNotSupported: return "The version of the underlying socket provider is out of range.";
                case SocketError.NotInitialized: return "The underlying socket provider has not been initialized.";
                case SocketError.Disconnecting: return "A graceful shutdown is in progress.";
                case SocketError.TypeNotFound: return "The specified class was not found.";
                case SocketError.HostNotFound: return "No such host is known. The name is not an official host name or alias.";
                case SocketError.TryAgain: return "The name of the host could not be resolved. Try again later.";
                case SocketError.NoRecovery: return "The error is unrecoverable or the requested database cannot be located.";
                case SocketError.NoData: return "The requested name or IP address was not found on the name server.";
                case SocketError.IOPending: return "The application has initiated an overlapped operation that cannot be completed immediately.";
                case SocketError.OperationAborted: return "The overlapped operation was aborted due to the closure of the Socket.";
            }

            return "Unknown Socket Error";
        }
        public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
        {
            Debug.Assert(_socketAddress != null);
            Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);

            _socketAddressSize = socketAddressSize;
            _socketFlags = receivedFlags;
            _ipPacketInformation = ipPacketInformation;

            base.CompletionCallback(numBytes, errorCode);
        }
Exemple #19
0
 // http://msdn.microsoft.com/ko-kr/library/vstudio/system.net.sockets.socketerror(v=vs.100).aspx
 public static bool IsIgnorableError(SocketError error)
 {
     if (error == SocketError.Interrupted
         || error == SocketError.ConnectionAborted
         || error == SocketError.ConnectionReset
         || error == SocketError.OperationAborted)
     {
         return true;
     }
     return false;
 }
 void Handle( SocketError se )
 {
     switch ( se ) {
     case SocketError.Success:
         return; // not an error
     case SocketError.ConnectionReset:
         if (AutoReconnect) BeginReconnect();
         break;
     }
     if ( OnSocketError != null ) OnSocketError(se);
 }
        private void HandleSocketError(SocketError error)
        {
            if (ConnectFailed != null)
                ConnectFailed(this, error);

            if (_connectTcs != null)
            {
                _connectTcs.SetResult(null);
                _connectTcs = null;
            }
        }
		public static Task<int> SendAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags flags, out SocketError error) {
			var tsc = new TaskCompletionSource<int> ();

			socket.BeginSend (buffer, offset, size, flags, out error, asyncResult => {
				try {
					tsc.SetResult (socket.EndSend (asyncResult));
				} catch (Exception e) {
					tsc.SetException (e);
				}
			}, null);

			return tsc.Task;
		}
 private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     foreach (var listener in _connectionEventListeners)
     {
         try
         {
             listener.OnConnectionClosed(connection, socketError);
         }
         catch (Exception ex)
         {
             _logger.Error(string.Format("Notify connection closed failed, listener type:{0}", listener.GetType().Name), ex);
         }
     }
 }
Exemple #24
0
        /// <summary>
        /// Create and return a new NetMQException with no Message containing the given SocketError and Exception.
        /// </summary>
        /// <param name="error">a SocketError that this exception will carry and expose via its ErrorCode property</param>
        /// <param name="innerException">an Exception that this exception will expose via its InnerException property</param>
        /// <returns>a new NetMQException</returns>
        
        public static NetMQException Create(SocketError error,  Exception innerException = null)
        {
            var errorCode = error.ToErrorCode();

#if DEBUG
            if (errorCode == 0)
            {
                var s = string.Format("(And within NetMQException.Create: Unanticipated error-code: {0})", error.ToString());
                return Create(errorCode: errorCode, message: s, innerException: innerException);
            }
#endif

            return Create(errorCode, innerException);
        }
Exemple #25
0
 public static ErrorCode SocketErrorToErrorCode(SocketError error)
 {
     switch (error)
     {
         case SocketError.AccessDenied:
             return ErrorCode.EACCESS;
         case SocketError.Fault:
             return ErrorCode.EFAULT;
         case SocketError.InvalidArgument:
             return ErrorCode.EINVAL;
         case SocketError.TooManyOpenSockets:
             return ErrorCode.EMFILE;
         case SocketError.InProgress:
             return ErrorCode.EAGAIN;
         case SocketError.MessageSize:
             return ErrorCode.EMSGSIZE;
         case SocketError.ProtocolNotSupported:
             return ErrorCode.EPROTONOSUPPORT;
         case SocketError.AddressFamilyNotSupported:
             return ErrorCode.EAFNOSUPPORT;
         case SocketError.AddressAlreadyInUse:
             return ErrorCode.EADDRINUSE;
         case SocketError.AddressNotAvailable:
             return ErrorCode.EADDRNOTAVAIL;
         case SocketError.NetworkDown:
             return ErrorCode.ENETDOWN;
         case SocketError.NetworkUnreachable:
             return ErrorCode.ENETUNREACH;
         case SocketError.NetworkReset:
             return ErrorCode.ENETRESET;
         case SocketError.ConnectionAborted:
             return ErrorCode.ECONNABORTED;
         case SocketError.ConnectionReset:
             return ErrorCode.ECONNRESET;
         case SocketError.NoBufferSpaceAvailable:
             return ErrorCode.ENOBUFS;
         case SocketError.NotConnected:
             return ErrorCode.ENOTCONN;
         case SocketError.TimedOut:
             return ErrorCode.ETIMEDOUT;
         case SocketError.ConnectionRefused:
             return ErrorCode.ECONNREFUSED;
         case SocketError.HostUnreachable:
             return ErrorCode.EHOSTUNREACH;
         default:
             Debug.Assert(false);
             return 0;
     }
 }
Exemple #26
0
		private void OnConnected(long channelId, SocketError error)
		{
			if (this.service.GetChannel(channelId) == null)
			{
				return;
			}
			if (error != SocketError.Success)
			{
				Log.Error($"connect error: {error}");
				return;
			}
			this.isConnected = true;
			this.StartSend();
			this.StartRecv();
		}
Exemple #27
0
 /// <summary>
 /// Return the ErrorCode that is the closest equivalent to the given SocketError.
 /// </summary>
 /// <param name="error">the SocketError to convert from</param>
 /// <returns>an ErrorCode that corresponds to the given SocketError</returns>
 public static ErrorCode SocketErrorToErrorCode(SocketError error)
 {
     switch (error)
     {
         case SocketError.AccessDenied:
             return ErrorCode.AccessDenied;
         case SocketError.Fault:
             return ErrorCode.Fault;
         case SocketError.InvalidArgument:
             return ErrorCode.Invalid;
         case SocketError.TooManyOpenSockets:
             return ErrorCode.TooManyOpenSockets;
         case SocketError.InProgress:
             return ErrorCode.TryAgain;
         case SocketError.MessageSize:
             return ErrorCode.MessageSize;
         case SocketError.ProtocolNotSupported:
             return ErrorCode.ProtocolNotSupported;
         case SocketError.AddressFamilyNotSupported:
             return ErrorCode.AddressFamilyNotSupported;
         case SocketError.AddressNotAvailable:
             return ErrorCode.AddressNotAvailable;
         case SocketError.NetworkDown:
             return ErrorCode.NetworkDown;
         case SocketError.NetworkUnreachable:
             return ErrorCode.NetworkUnreachable;
         case SocketError.NetworkReset:
             return ErrorCode.NetworkReset;
         case SocketError.ConnectionAborted:
             return ErrorCode.ConnectionAborted;
         case SocketError.ConnectionReset:
             return ErrorCode.ConnectionReset;
         case SocketError.NoBufferSpaceAvailable:
             return ErrorCode.NoBufferSpaceAvailable;
         case SocketError.NotConnected:
             return ErrorCode.NotConnected;
         case SocketError.TimedOut:
             return ErrorCode.TimedOut;
         case SocketError.ConnectionRefused:
             return ErrorCode.ConnectionRefused;
         case SocketError.HostUnreachable:
             return ErrorCode.HostUnreachable;
         default:
             Debug.Assert(false);
             return 0;
     }
 }
        public void CompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressLen, SocketError errorCode)
        {
            _buffer = null;
            _localBytesTransferred = 0;

			if (errorCode == SocketError.Success)
			{
				Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint);
				System.Buffer.BlockCopy(socketAddress, 0, remoteSocketAddress.Buffer, 0, socketAddressLen);

				_acceptedSocket = _listenSocket.CreateAcceptSocket(
					SafeCloseSocket.CreateSocket(acceptedFileDescriptor),
					_listenSocket._rightEndPoint.Create(remoteSocketAddress));
			}

            base.CompletionCallback(0, errorCode);
        }
 public MailExceptionEx(MailStatus status, MailCause cause, object baseException)
 {
     this.InitOption(status, cause);
     if (baseException.GetType() == typeof(TimeoutException))
     {
         this.mException = ((TimeoutException) baseException).GetBaseException();
     }
     else if (baseException.GetType() == typeof(SocketException))
     {
         this.mException = (SocketException) baseException;
         this.mSocketErrorCode = ((SocketException) baseException).ErrorCode;
         this.mSocketErrorCodeType = ((SocketException) baseException).SocketErrorCode;
     }
     else
     {
         this.mException = (Exception) baseException;
     }
 }
        // This method is called after an asynchronous call is made for the user.
        // It checks and acts accordingly if the IO:
        // 1) completed synchronously.
        // 2) was pended.
        // 3) failed.
        internal unsafe SocketError CheckAsyncCallOverlappedResult(SocketError errorCode)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, errorCode);

            if (errorCode == SocketError.Success || errorCode == SocketError.IOPending)
            {
                // Ignore cases in which a completion packet will be queued:
                // we'll deal with this IO in the callback.
                return SocketError.Success;
            }

            // In the remaining cases a completion packet will NOT be queued:
            // we have to call the callback explicitly signaling an error.
            ErrorCode = (int)errorCode;
            Result = -1;

            ReleaseUnmanagedStructures();  // Additional release for the completion that won't happen.
            return errorCode;
        }
Exemple #31
0
 protected override void OnError(SocketError error)
 {
     Console.WriteLine($"Server caught an error with code {error}");
 }
Exemple #32
0
 public abstract bool Receive(out int bytesTransferred, out SocketError socketError, Action <int, SocketError> onSendCallback);
Exemple #33
0
        public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, int receivedFlags, SocketError errorCode)
        {
            if (_socketAddress != null)
            {
                Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);
                _socketAddressSize = socketAddressSize;
            }

            base.CompletionCallback(numBytes, errorCode);
        }
Exemple #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DisconnectedEventArgs"/> class.
        /// </summary>
        /// <param name="error">Reason to disconnection.</param>
        public DisconnectedEventArgs(SocketError error)
        {
            Check.Require(error, "error");

            Error = error;
        }
Exemple #35
0
 public SocketException(SocketError errorCode)
     : this(errorCode.ToString(), errorCode)
 {
 }
Exemple #36
0
        public void MainLoop()
        {
            try
            {
                bool shutdownCleanly = false;
                try
                {
                    while (m_running)
                    {
                        try
                        {
                            MainLoopIteration();
                        }
                        catch (SoftProtocolException spe)
                        {
                            QuiesceChannel(spe);
                        }
                    }
                    shutdownCleanly = true;
                }
                catch (EndOfStreamException eose)
                {
                    // Possible heartbeat exception
                    HandleMainLoopException(new ShutdownEventArgs(
                                                ShutdownInitiator.Library,
                                                0,
                                                "End of stream",
                                                eose));
                }
                catch (HardProtocolException hpe)
                {
                    shutdownCleanly = HardProtocolExceptionHandler(hpe);
                }
#if !NETFX_CORE
                catch (Exception ex)
                {
                    HandleMainLoopException(new ShutdownEventArgs(ShutdownInitiator.Library,
                                                                  Constants.InternalError,
                                                                  "Unexpected Exception",
                                                                  ex));
                }
#endif

                // If allowed for clean shutdown, run main loop until the
                // connection closes.
                if (shutdownCleanly)
                {
#pragma warning disable 0168
                    try
                    {
                        ClosingLoop();
                    }
#if NETFX_CORE
                    catch (Exception ex)
                    {
                        if (SocketError.GetStatus(ex.HResult) != SocketErrorStatus.Unknown)
                        {
                            // means that socket was closed when frame handler
                            // attempted to use it. Since we are shutting down,
                            // ignore it.
                        }
                        else
                        {
                            throw ex;
                        }
                    }
#else
                    catch (SocketException se)
                    {
                        // means that socket was closed when frame handler
                        // attempted to use it. Since we are shutting down,
                        // ignore it.
                    }
#endif
#pragma warning restore 0168
                }

                FinishClose();
            }
            finally
            {
                m_appContinuation.Set();
            }
        }
Exemple #37
0
 public void OnNetworkError(IPEndPoint endPoint, SocketError error)
 {
     Console.WriteLine("[Client] error! " + error);
 }
Exemple #38
0
 /// <summary>
 /// Handle error notification
 /// </summary>
 /// <param name="error">Socket error code</param>
 protected virtual void OnError(SocketError error)
 {
 }
Exemple #39
0
 protected override void OnError(SocketError error)
 {
     Console.WriteLine($"Echo UDP client caught an error with code {error}");
 }
Exemple #40
0
 private void RegistrationTransactionFailed(SIPTransaction sipTransaction, SocketError failureReason)
 {
     m_isRegistered = false;
     RegistrationTemporaryFailure?.Invoke(m_sipAccountAOR, $"Registration transaction to {m_registrarHost} for {m_sipAccountAOR} failed with {failureReason}.");
     m_waitForRegistrationMRE.Set();
 }
Exemple #41
0
 public bool Send(byte[] buffer, out SocketError code)
 {
     return(Send(buffer, 0, buffer.Length, out code));
 }
Exemple #42
0
 protected override void OnError(SocketError error)
 {
     SessionHandler.OnStateChanged(Id, ServerNetSessionState.Error);
 }
Exemple #43
0
        protected override void OnCloseClientsocket(ClientSession clientSession, SocketError error)
        {
            clientSession.OnRemoved();


            lock (_lockSessionContainer)
            {
                _authedClientSessions.Remove(clientSession.SessionId);


                // 재연결 대기 목록에 추가한다.
                if (clientSession.DisconnectState == ESessionState.None ||
                    clientSession.DisconnectState == ESessionState.Wait)
                {
                    clientSession.NetState      = ENetState.Reconnecting;
                    clientSession.AliveTimeTick = DateTime.UtcNow.AddSeconds(15).Ticks;

                    if (_reconnectClientSessions.Contains(clientSession) == true)
                    {
                        _logger.Fatal(string.Format("[CloseClientsocket] already exist reconnect session. clientSessionId: {0}", clientSession.SessionId));
                        return;
                    }

                    _reconnectClientSessions.Insert(0, clientSession);
                    _logger.Info(string.Format("[CloseClientsocket] reconnect session. clientSessionId: {0}", clientSession.SessionId));
                }
                else
                {
                    if (_expiredClientSessions.Exists(x => x == clientSession.SessionId) == false)
                    {
                        if (clientSession.NetState != ENetState.Reconnecting)
                        {
                            _expiredClientSessions.Add(clientSession.SessionId);
                        }
                    }
                    _logger.Info(string.Format("[CloseClientsocket] expired session. clientSessionId: {0}", clientSession.SessionId));
                }


                //
                if (_authedClientSessions.Count == 0)
                {
                    EndGameSession();
                }
            }


            clientSession.NetState = ENetState.Disconnected;
            if (ClientOfflineCallback != null && clientSession.GetPeer() != null)
            {
                ClientOfflineCallback(clientSession, clientSession.DisconnectState);
            }


            if (_receiveEventAragePool != null)
            {
                _receiveEventAragePool.Push(clientSession.ReceiveEventArgs);
            }

            if (_sendEventAragePool != null)
            {
                _sendEventAragePool.Push(clientSession.SendEventArgs);
            }

            _logger.Info(string.Format("[CloseClientsocket] _receiveEventAragePool: {0}, _sendEventAragePool: {1}", _receiveEventAragePool.Count, _sendEventAragePool.Count));
        }
Exemple #44
0
        private void HandleCompletionStatus(out CompletionStatus completionStatus, IntPtr overlappedAddress, IntPtr completionKey, int bytesTransferred)
        {
            if (completionKey.Equals(SignalPostCompletionKey))
            {
                object state;

                m_signalQueue.TryDequeue(out state);
                completionStatus = new CompletionStatus(null, state, OperationType.Signal, SocketError.Success, 0);
            }
            else
            {
                var overlapped = Overlapped.CompleteOperation(overlappedAddress);

                if (completionKey.Equals(SocketCompletionKey))
                {
                    // if the overlapped ntstatus is zero we assume success and don't call get overlapped result for optimization
                    if (overlapped.Success)
                    {
                        SocketError socketError = SocketError.Success;
                        try
                        {
                            if (overlapped.OperationType == OperationType.Accept)
                            {
                                overlapped.AsyncSocket.UpdateAccept();
                            }
                            else if (overlapped.OperationType == OperationType.Connect)
                            {
                                overlapped.AsyncSocket.UpdateConnect();
                            }
                        }
                        catch (SocketException ex)
                        {
                            socketError = ex.SocketErrorCode;
                        }

                        completionStatus = new CompletionStatus(overlapped.AsyncSocket, overlapped.State,
                                                                overlapped.OperationType, socketError,
                                                                bytesTransferred);
                    }
                    else
                    {
                        SocketError socketError = SocketError.Success;
                        SocketFlags socketFlags;
                        if (overlapped.Disposed)
                        {
                            socketError = SocketError.OperationAborted;
                        }
                        else
                        {
                            bool operationSucceed = UnsafeMethods.WSAGetOverlappedResult(overlapped.AsyncSocket.Handle,
                                                                                         overlappedAddress,
                                                                                         out bytesTransferred, false, out socketFlags);

                            if (!operationSucceed)
                            {
                                socketError = (SocketError)Marshal.GetLastWin32Error();
                            }
                        }
                        completionStatus = new CompletionStatus(overlapped.AsyncSocket, overlapped.State,
                                                                overlapped.OperationType, socketError,
                                                                bytesTransferred);
                    }
                }
                else
                {
                    completionStatus = new CompletionStatus(overlapped.AsyncSocket, overlapped.State,
                                                            overlapped.OperationType, SocketError.Success, 0);
                }
            }
        }
Exemple #45
0
 public void OnNetworkError(IPEndPoint endPoint, SocketError socketErrorCode)
 {
     Console.WriteLine("[Server] error: " + socketErrorCode);
 }
Exemple #46
0
 protected override void OnError(SocketError error)
 {
     log.Error($"TCP session caught an error with code {error}");
 }
Exemple #47
0
        public void OnNetworkError(IPEndPoint endPoint, SocketError socketError)
        {
            Debug.Log($"Error {socketError} for {endPoint} endpoint");

            // if master != null then raise exceptions
        }
 /// <summary>
 /// Invoked when we've been disconnected
 /// </summary>
 /// <param name="error"><see cref="SocketError.Success"/> means that we disconnected, all other codes indicates network failure or that the remote end point disconnected.
 ///
 /// </param>
 /// <remarks>Remember to call the <c>base</c> when you override this method (to trigger the Disconnected event)</remarks>
 protected virtual void OnDisconnect(SocketError error)
 {
     Disconnected(this, new DisconnectEventArgs(error));
 }
Exemple #49
0
        /*
         *  同步方式接受多个消息
         *      如果当前有可读消息,则立刻返回,否则超时等待设置的时间
         */
        private List <NetPacket> RecvPacketList()
        {
            // 检查连接状态
            if (!IsConnected())
            {
                SuperDebug.Warning(DebugPrefix.Network, "client is not connected, can not recv now.");
                return(null);
            }

            // 开始接受数据
            List <NetPacket> list = new List <NetPacket>();

            try
            {
                // 接受到缓存
                byte[]      recv_buf = new byte[ClientDefine.g_recv_buf_size - left_buf_len_];
                SocketError error    = new SocketError();
                int         recv_len = socket_.Receive(recv_buf, 0, recv_buf.Length, SocketFlags.None, out error);

                // 接受超时立刻返回
                if (error == SocketError.TimedOut ||
                    error == SocketError.WouldBlock ||
                    error == SocketError.IOPending)
                {
                    return(list);
                }

                // 如果接受数据长度为0,则表示连接出现异常,需要立刻使用回调函数通知使用方
                if (error != SocketError.Success || 0 == recv_len)
                {
                    SuperDebug.Warning(DebugPrefix.Network, "recv failed with recv_len=" + recv_len + ", error=" + error);
                    socket_.Close();
                    socket_ = null;
                    return(list);
                }

                // 合并上次剩余、本次收到的数据
                byte[] total_buf = new byte[ClientDefine.g_recv_buf_size];
                Array.Copy(left_buf_, 0, total_buf, 0, left_buf_len_);
                Array.Copy(recv_buf, 0, total_buf, left_buf_len_, recv_len);
                int total_len = recv_len + left_buf_len_;
                left_buf_len_ = 0;

                // 开始处理
                int used = 0;

                // 一次可能recv多个packet,循环反序列化每个packet,并加入list
                while (used < total_len)
                {
                    //缓存之前的有效数据
                    if (_tempPacket == null)
                    {
                        _tempPacket = new NetPacket();
                    }

                    PacketStatus packet_status = _tempPacket.Deserialize(ref total_buf, ref used, total_len);

                    if (PacketStatus.PACKET_CORRECT != packet_status)
                    {
                        // 存储残缺的数据
                        if (PacketStatus.PACKET_NOT_COMPLETE == packet_status)
                        {
                            left_buf_len_ = total_len - used;
                            Array.Copy(total_buf, used, left_buf_, 0, left_buf_len_);
                        }
                        else
                        {
                            SuperDebug.Warning(DebugPrefix.Network, "deserialize packet failed. " + packet_status);
                        }

                        break;
                    }
                    else
                    {
                        list.Add(_tempPacket);
                        _tempPacket = null;
                    }
                }
            }
            catch (SystemException e)
            {
                if (IsConnected())
                {
                    SuperDebug.Error(DebugPrefix.Network, "recv failed: " + e);
                }
            }
            return(list);
        }
Exemple #50
0
        async void UDPMulticastMessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            try
            {
                uint   stringLength = eventArguments.GetDataReader().UnconsumedBufferLength;
                string message      = eventArguments.GetDataReader().ReadString(stringLength);
                string Command      = CompanionProtocol.GetCommandFromMessage(message);
                Dictionary <string, string> Parameters = CompanionProtocol.GetParametersFromMessage(message);
                CompanionDevice             d          = GetCompanionDeviceFromParameters(Parameters);
                System.Diagnostics.Debug.WriteLine("Received command: " + message);

                if (string.Equals(Command, CompanionProtocol.commandPingResponse))
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        if (d != null)
                        {
                            var searchDevice = listCompanionDevices.FirstOrDefault(device => string.Equals(device.Value.Name, d.Name));
                            if (searchDevice.Value == null)
                            {
                                // Add Device
                                d.Status = CompanionDeviceStatus.Connected;
                                if (string.IsNullOrEmpty(d.Id))
                                {
                                    d.Id = Guid.NewGuid().ToString();
                                }
                                if (listCompanionDevices.ContainsKey(d.Id))
                                {
                                    listCompanionDevices.Remove(d.Id);
                                }
                                listCompanionDevices.Add(d.Id, d);
                                OnDeviceAdded(this, d);
                            }
                            else
                            {
                                if (!string.Equals(d.IPAddress, searchDevice.Value.IPAddress))
                                {
                                    d.Id     = searchDevice.Value.Id;
                                    d.Status = CompanionDeviceStatus.Connected;
                                    listCompanionDevices.Remove(d.Id);
                                    listCompanionDevices.Add(d.Id, d);
                                    // Update device
                                    OnDeviceUpdated(this, d);
                                }
                            }
                        }
                    });
                }
                else if (string.Equals(Command, CompanionProtocol.commandPing))
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                    {
                        if (d != null)
                        {
                            /*
                             * var searchDevice = listCompanionDevices.FirstOrDefault(device => string.Equals(device.Value.Name, d.Name) );
                             * if (searchDevice.Value == null)
                             * {
                             *  d.Status = CompanionDeviceStatus.Connected;
                             *  listCompanionDevices.Add(d.Id, d);
                             *  if (CompanionDeviceAdded != null)
                             *      CompanionDeviceAdded(this, d);
                             * }
                             * else
                             * {
                             *  if ((!string.Equals(d.Id, searchDevice.Value.Id)) ||
                             *      (!string.Equals(d.IPAddress, searchDevice.Value.IPAddress)))
                             *  {
                             *      d.Id = searchDevice.Value.Id;
                             *      d.Status = CompanionDeviceStatus.Connected;
                             *      listCompanionDevices.Remove(d.Id);
                             *      listCompanionDevices.Add(d.Id, d);
                             *      // Update device
                             *      if (CompanionDeviceUpdated != null)
                             *          CompanionDeviceUpdated(this, d);
                             *  }
                             * }
                             */
                            Dictionary <string, string> parameters = new Dictionary <string, string>();
                            if (parameters != null)
                            {
                                parameters.Add(CompanionProtocol.parameterID, LocalCompanionDevice.Id);
                                parameters.Add(CompanionProtocol.parameterIPAddress, LocalCompanionDevice.IPAddress);
                                parameters.Add(CompanionProtocol.parameterKind, LocalCompanionDevice.Kind);
                                parameters.Add(CompanionProtocol.parameterName, LocalCompanionDevice.Name);
                                string m = CompanionProtocol.CreateCommand(CompanionProtocol.commandPingResponse, parameters);
                                await Send(d.IPAddress, m);
                            }
                        }
                    });
                }
                else
                {
                    // Forward the Message
                    if (MessageReceived != null)
                    {
                        MessageReceived(d, message);
                    }
                }
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine("Exception on receiving UDP packets: " + exception.Message);
                SocketErrorStatus socketError = SocketError.GetStatus(exception.HResult);
                if (socketError == SocketErrorStatus.ConnectionResetByPeer)
                {
                }
                else if (socketError != SocketErrorStatus.Unknown)
                {
                }
            }
        }
Exemple #51
0
 public SocketException(string message,
                        SocketError errorCode = SocketError.Fatal)
     : this(message, null, errorCode)
 {
 }
Exemple #52
0
        async Task <bool> Send(string ip, string Message)
        {
            try
            {
                if (msocketSend == null)
                {
                    return(false);
                }

                // Add Device Information
                string command = CompanionProtocol.GetCommandFromMessage(Message);
                Dictionary <string, string> parameters = CompanionProtocol.GetParametersFromMessage(Message);
                if (!string.IsNullOrEmpty(command))
                {
                    if (parameters == null)
                    {
                        parameters = new Dictionary <string, string>();
                    }
                    if ((parameters != null) && (!parameters.ContainsKey(CompanionProtocol.parameterIPAddress)) &&
                        (!parameters.ContainsKey(CompanionProtocol.parameterName)) &&
                        (!parameters.ContainsKey(CompanionProtocol.parameterKind)) &&
                        (!parameters.ContainsKey(CompanionProtocol.parameterID)))
                    {
                        parameters.Add(CompanionProtocol.parameterID, LocalCompanionDevice.Id);
                        parameters.Add(CompanionProtocol.parameterIPAddress, LocalCompanionDevice.IPAddress);
                        parameters.Add(CompanionProtocol.parameterKind, LocalCompanionDevice.Kind);
                        parameters.Add(CompanionProtocol.parameterName, LocalCompanionDevice.Name);

                        Message = CompanionProtocol.CreateCommand(command, parameters);
                    }
                }
                HostName mcast;
                string   port;
                if ((string.IsNullOrEmpty(ip)) || (string.Equals(ip, MulticastIPAddress)))
                {
                    port  = MulticastUDPPort.ToString();
                    mcast = new HostName(MulticastIPAddress);
                }
                else
                {
                    port  = UnicastUDPPort.ToString();
                    mcast = new HostName(ip);
                }
                DataWriter writer = new DataWriter(await msocketSend.GetOutputStreamAsync(mcast, port));

                if (writer != null)
                {
                    writer.WriteString(Message);
                    uint result = await writer.StoreAsync();

                    bool bresult = await writer.FlushAsync();

                    writer.DetachStream();
                    writer.Dispose();
                    System.Diagnostics.Debug.WriteLine("Message Sent to: " + mcast.CanonicalName + ":" + port + " content: " + Message);
                    return(true);
                }
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    return(false);
                }
                return(false);
            }
            return(false);
        }
 public void OnNetworkError(IPEndPoint endPoint, SocketError error)
 {
     Log.Warning($"Net client error {error}");
 }
        /// <summary>
        /// Thread를 끝내지 않고 connection만 끝낸다.
        /// 이 명령은 ConnectionEvent를 발생시키지 않지만 PermanantConnection모드에서는
        /// 다시 접속을 시도한다.
        /// </summary>
        public void Disconnect(Func <int> funcRunningBeforeCloseSocket = null)
        {
            releaseResources();

            if (_server != null && _server.Client != null)
            {
                if (_server.Client.Blocking)
                {
                    _server.Client.Blocking = false;
                }
                Win32APIs.SendMsgData("Blocking 해제...", "LogWindow");
            }


            if (_server != null && _server.Client != null)
            {
                Byte[]      buff  = new Byte[1];
                SocketError error = SocketError.NoData;
                _server.SendTimeout = 1000;
                if (funcRunningBeforeCloseSocket != null)
                {
                    funcRunningBeforeCloseSocket.Invoke();
                }


                //int recv = _server.Client.Send(buff, 0, 1, SocketFlags.None, out error);
                //Win32APIs.SendMsgData("1byte 보낸 것 성공?"+recv+"\r\n", "LogWindow");
                //if (error != SocketError.Success)
                //{
                //   Win32APIs.SendMsgData("소켓손상...", "LogWindow");
                //이미 소켓이 손상된 경우..
                // _server = null;
                //}
                //else {//끝내기 전에 사용자가 원하는 작업 한 가지를 하고 끝낼 수 있다.

                try
                {
                    Win32APIs.SendMsgData("disconnect시도", "LogWindow");
                    try
                    {
                        _server.Client.Disconnect(false);
                        Win32APIs.SendMsgData("disconnect완료", "LogWindow");
                    }
                    catch (Exception ex)
                    {
                        Win32APIs.SendMsgData("disconnect시 에러:" + ex.Message, "LogWindow");
                    }
                    Win32APIs.SendMsgData("close시도", "LogWindow");
                    _server.Client.Close(1000);
                    Win32APIs.SendMsgData("close완료", "LogWindow");
                }
                catch (Exception e) {
                    Win32APIs.SendMsgData("close시 에러..\r\n" + e.Message, "LogWindow");
                }

                //}
            }
            //미리 삭제된 개체였을 가능성..
            _server          = null;
            _connectionState = ConnType.Disconnected;
            //ConnectionEvent(ConnType.Disconnected);
        }
 private void OnConnectionClosed(TcpTypedConnection connection, IPEndPoint endPoint, SocketError error)
 {
     lock (_connectionLock)
         _reconnectionStopwatch.Restart();
 }
 public void CompletionCallback(int numBytes, SocketError errorCode)
 {
     ErrorCode = (int)errorCode;
     InvokeCallback(PostCompletion(numBytes));
 }
Exemple #57
0
 public void InCompleted(SocketError socketError, int bytesTransferred)
 {
     throw new NotImplementedException();
 }
Exemple #58
0
 protected override void OnError(SocketError error)
 {
     Console.WriteLine($"Client caught an error with code {error}");
     Program.TotalErrors++;
 }
Exemple #59
0
        public int SendTo(byte[] data, int offset, int size, IPEndPoint remoteEndPoint, ref SocketError errorCode)
        {
            try
            {
                var socket = _udpSocketv4;
                if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support)
                {
                    socket = _udpSocketv6;
                }
                int result = socket.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint);
                NetDebug.Write(NetLogLevel.Trace, "[S]Send packet to {0}, result: {1}", remoteEndPoint, result);
                return(result);
            }
            catch (SocketException ex)
            {
                switch (ex.SocketErrorCode)
                {
                case SocketError.NoBufferSpaceAvailable:
                case SocketError.Interrupted:
                    return(0);

                case SocketError.MessageSize:     //do nothing
                    break;

                default:
                    NetDebug.WriteError("[S]" + ex);
                    break;
                }
                errorCode = ex.SocketErrorCode;
                return(-1);
            }
            catch (Exception ex)
            {
                NetDebug.WriteError("[S]" + ex);
                return(-1);
            }
        }
        /// <summary>
        /// Reads a new serialized message object from the base stream and deserializes it.
        /// </summary>
        /// <param name="readTimeOutSeconds">Optional read timeout in seconds  (0 means no timeout).</param>
        /// <returns>
        /// The deserialized object if successful, <c>null</c> otherwise.
        /// </returns>
        public object Read(int readTimeOutSeconds = 0)
        {
            try
            {
                lock (_readSerializerMap)
                {
                    if (_readSerializerMap.Count == 0)
                    {
                        return(false);
                    }

                    XmlSerializer serializer = null;
                    byte[]        message    = null;

                    bool isUnprocessedMessage = false;

                    do
                    {
                        if ((message = _stream.Read(readTimeOutSeconds)) == null)
                        {
                            return(null);
                        }

                        int    descriptorLength  = (message.Length < TypeDescriptorMaxLength) ? message.Length : TypeDescriptorMaxLength;
                        string typeDescriptor    = Encoding.UTF8.GetString(message, 0, descriptorLength);
                        Match  objectTypeMatch   = _messageObjectTypeRegex.Match(typeDescriptor);
                        string messageObjectType = objectTypeMatch.Groups["objectType"].Value;

                        isUnprocessedMessage = (String.Equals(messageObjectType, typeof(UnprocessedMessage).Name));

                        if ((objectTypeMatch.Success == false) || (string.IsNullOrWhiteSpace(messageObjectType)))
                        {
                            this.Error($"The read object does not have a valid type: { Environment.NewLine }'{ typeDescriptor }'{ Environment.NewLine }");

                            if (isUnprocessedMessage == false)
                            {
                                this.Write(Utils.CreateUnprocessedMessage(Encoding.UTF8.GetString(message), UnprocessedMessageReason.SyntaxError));
                            }
                            return(null);
                        }

                        messageObjectType = messageObjectType.Trim().ToLower();

                        if (_readSerializerMap.ContainsKey(messageObjectType) == false)
                        {
                            this.Error("The object type '{0}' is not supported.", messageObjectType);

                            if (isUnprocessedMessage == false)
                            {
                                this.Write(Utils.CreateUnprocessedMessage(Encoding.UTF8.GetString(message), UnprocessedMessageReason.NotSupported));
                            }
                        }
                        else
                        {
                            serializer = _readSerializerMap[messageObjectType];
                        }
                    }while (serializer == null);

                    using (MemoryStream ms = new MemoryStream(message))
                    {
                        try
                        {
                            return(serializer.Deserialize(ms));
                        }
                        catch (Exception ex)
                        {
                            this.Error("Fail to deserialize message, Ingored \r\n {0} \r\n {1}", Encoding.UTF8.GetString(message), ex);

                            if (isUnprocessedMessage == false)
                            {
                                this.Write(Utils.CreateUnprocessedMessage(Encoding.UTF8.GetString(message), UnprocessedMessageReason.SyntaxError));
                            }
                            return(Read(readTimeOutSeconds));
                        }
                    }
                }
            }catch (IOException ex)
            {
                SocketException socketException = ex.InnerException as SocketException;

                if (socketException != null)
                {
                    SocketError socketError = socketException.SocketErrorCode;

                    this.Error($"Reading serialized object failed because of socket interruption. Error: { socketError.ToString() }", ex);
                }
            }catch (Exception ex)
            {
                this.Error("Reading serialized object failed.", ex);
                this.Write(Utils.CreateUnprocessedMessage(ex.Message, UnprocessedMessageReason.NotSupported));
            }

            return(null);
        }