Example #1
0
        void SendPacket()
        {
            if (Send)
            {
                MainSocket.Send(Encoding.UTF8.GetBytes(Packet.OutBuffer), 0, Encoding.UTF8.GetBytes(Packet.OutBuffer).Length, 0, out socketError);
                StatusReport = "Sent Packet successfully";

                StatusReport = socketError.ToString();

                Send = false;
            }
        }
Example #2
0
        void SendPacket()
        {
            if (Send)
            {
                for (int i = 0; i < AcceptSockets.Count; i++)
                {
                    AcceptSockets[i].Send(Encoding.UTF8.GetBytes(Packet.OutBuffer), 0, Encoding.UTF8.GetBytes(Packet.OutBuffer).Length, 0, out socketError);
                    StatusReport = socketError.ToString();
                }

                Send = false;
            }
        }
Example #3
0
    private void Received_Callback(IAsyncResult result)
    {
        if (Socket_Client == null || IsConnected == false)
        {
            return;
        }

        //콜백 함수를 한번 등록했는데 2번 연속 호출되는 경우의 폰들이 있기때문에 체크후 막아준다.
        //2번째 호출되는 콜백함수의 들어온 값은 이전과 동일하다고 믿는 전제하에 막는것임.
        //연속되게 들어온 데이터가 이전과 동일한지는 모른다
        if (BeginReceive_Start_Check == false)
        {
            return;
        }
        BeginReceive_Start_Check = false;

        try
        {
            EndReceive_Length = Socket_Client.EndReceive(result, out SocketErrorCode);

            if (SocketErrorCode != SocketError.Success)
            {
                //Debug.Log("EndReceive_Length = " + EndReceive_Length + ", LENGTH = " + LENGTH);

                Error_DisConnect(SocketErrorCode.ToString());

                return;
            }

            if (EndReceive_Length <= 0)
            {
                //Debug.LogError("받은 데이터가 0 값이다!!! Received_Callback() EndReceive_Length = " + EndReceive_Length);

                BeginReceive_Init();

                return;
            }

            //토탈 버퍼에 담아서 받은 패킷 나눠주는 처리 한다.
            Total_Recv_Operation(EndReceive_Length, (byte[])result.AsyncState);

            BeginReceive_Init();
        }
        catch (Exception ex)
        {
            Error_DisConnect(ex);
        }
    }
Example #4
0
        private static bool checkReadyEx()
        {
            if (isValid())
            {
                if ((mLastConnectedTimestamp != 0.0) && (SessionPack.getNow() > (mLastConnectedTimestamp + 30000.0)))
                {
                    EventCenter.postEvent(EventConst.ON_NET_LONGCONN_KEEPALIVE, null, null);
                    mLastConnectedTimestamp = 0.0;
                }
                return(true);
            }
            if (mReconnectLeft <= 0)
            {
                if (mReconnectLeft == 0)
                {
                    Log.e("Network", "no chance to try connect.");
                    mReconnectLeft = -1;
                }
                return(false);
            }
            double num  = SessionPack.getNow();
            double num2 = mLastConnTimestamp + getSleepTime(mReconnectLeft);

            if ((mReconnectLeft == 3) || (num >= num2))
            {
                mLastConnTimestamp = num;
                mReconnectLeft--;
                Connector.setConnectorStatus(ConntectorStatus.Connecting);
                mSocketClient = new SocketClient();
                HostService.HostInfo info  = HostService.mLongConnHosts.getAvailableHost();
                SocketError          error = mSocketClient.Connect(info.mHost, info.mPort);
                if (error == ((SocketError)((int)SocketError.Success)))
                {
                    Log.i("Network", "connect success.");
                    mLastConnectedTimestamp = num;
                    //NetworkDeviceWatcher.onConnected();
                    mReconnectLeft = 2;
                    mFirstKeepAlivePointAfterConnected = restartKeepAlivePoint(0xbb8);
                    mConnFailedCount = 0;
                    Connector.setConnectorStatus(ConntectorStatus.Connected);
                    return(true);
                }
                if (error == ((SocketError)((int)SocketError.HostNotFound)))
                {
                    HostService.setDNSFailed();
                }
                Log.e("Network", "connect error:" + error.ToString());
                close();
                mConnFailedCount++;
                if (mConnFailedCount >= 3)
                {
                    Log.i("Network", "longconnect is not available as connect failed(3/3).");
                    setAvailable(false);
                    mConnFailedCount = 0;
                }
                HostService.mLongConnHosts.onCurrentHostFailed();
                Connector.setConnectorStatus(ConntectorStatus.Disconnect);
            }
            return(false);
        }
Example #5
0
        public static bool sendPack(SessionPack sessionPack)
        {
            if (mSocketClient == null)
            {
                return(false);
            }
            NetPack.Request request = new NetPack.Request(sessionPack.mSeqID, sessionPack.mCmdID, sessionPack.mCacheBodyBuffer);

            // NetPack.Request request = new NetPack.Request(1, 701, Util.HexStringToByte("bf8e7f1603181100000000000000000000000000000000000000bd05b007b00787010d0000012b0000024c000002004b8116d636cdcf7c1eac04e1427a78c784acc68ed332c2475ae778918ef43170db0d46c3c7f7bacf1c14f2385438cb8e066083dd24d355d93cea6bf159ea20a309be99a125f26f8e8726504e8616533924faebd1ef985bf05876ac59513b1eca83696d87b1f7519754176fbf12e9f51e2e913469884f48419003e747416c7985d12abfad19b15bc3048322aea2ad801a2f8390262aab19a73bcd34199e0993c1659bad1d4859cb137892c179d536823e4418a4e8a06835a143b0416dda924e14f91a90567db32c0731f94844515779080789092025cdfbe12565a306b546c3daa2996e1670aa65456292c09d29f541cd2fe2fb8d9ad155f8b1824fad1037e7d058a1d36a69a8236f0230400316e98e314916fb197571e349a058a1d0ba7f36285a5aae4b54d4af84cd4579bfe1ceaa10a0d55875be281a56f98cb8fb59a51d58ad39d20f8513a8a14728409e9113cca6a90be4074b2f35000b45df07dc5d13fdc53a10793feb45f1ac1cbb56c3b744fe8dc7f1d8f2decd8886d324ddee3d58e4e5510042e4b319b93deae768cdd8d7f39fef00656e1f665e80e281ffe4f424a8d466309824a8479edc67693f8e769e5c97d7778c63a95507d60a901c1890fa9a1c6f5d7cb4fda44f454e81b3fc60c7c7582e2f888cde6f41a8c657566f8dbcdee4e97ba6f8681448e3c93308837cd5c6597e20d03757f5a24a5ff6bc4032566c14c753cef9f0b17e70fb1f96e75423b325badf3fdfff4c9d554b4ed29ff21c7545150190aa44b2a60c74634081c17f9a3ce36d299b7b04dc0c09f85ca71b61be02baee13841992b284ca5cd8fe0e6608d0158fcdb3b60706cef28350fd5998fddd19b9b4ccb661c7f4f5a9c80906dee68cb303da3519b5a1b588a6bc47af60cdf6f38cf28bbb1d0572bd23d6250fc15a64c39aabf50463b2e9d9b3d3059bff1466f137ffb62ebee8d29fe85f38d923b17f0c259e0dbb75c1a61f57f3e9006d6a9ae8159398c1883ab421174ebe646cce7952a65d09c1285288bb6132efc997846b6879a47448785eddac3e7ad705b020325b5faa19daeab8544e0b1a149b657a5f533d6ba31164c3a0203d6414496b098e77011602368b585527c7badc5f27df367bcc043718d3e613b5a0cdbe90eccb271f3d7bfc2393575df718c40b2d30263558a18edda94d12e50c770920223fe0b54c7b43354f052104db5364d1d825035d5da36a015b86fdf26301d0d214d717d14c9ff499a26e4e31976ff5c0b28c841ea0a42762638f245c12774c0f59b8a659f0c1a425aa1fbecfeb0648afc020fbf078a268a50c894b9674f6de085cfc2e"));

            byte[] outBuf = null;
            request.serializeToBuffer(ref outBuf);
            //FlowControl.onSend(sessionPack.mCmdID, sessionPack.mCmdUri, (uint) outBuf.Length);
            SocketError error = mSocketClient.Send(outBuf);

            // string a = Util.byteToHexStr(outBuf);
            sessionPack.timeInSent = Util.getNowMilliseconds();
            if (error != ((SocketError)((int)SocketError.Success)))
            {
                Log.e("Network", "Socket Send error : " + error.ToString());
                if ((error == ((SocketError)((int)SocketError.ConnectionAborted))) || (error == ((SocketError)((int)SocketError.ConnectionReset))))
                {
                    close();
                }
                return(false);
            }
            restartKeepAlivePoint(0xea60);
            return(true);
        }
        private bool ReadResponse(ModuleProc PROC)
        {
            bool result = false;

            try
            {
                byte[]      buffer          = new byte[RECEIVE_BUFFER_SIZE];
                SocketError socketErrorCode = SocketError.Success;
                int         bytesReceived   = _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None, out socketErrorCode);
                if (bytesReceived > 0 && (socketErrorCode == SocketError.Success))
                {
                    byte[] bufferCopy = new byte[bytesReceived];
                    Buffer.BlockCopy(buffer, 0, bufferCopy, 0, bufferCopy.Length);
                    result = this.OnReceivedBytes(this, bufferCopy);
                }
                else
                {
                    this.WriteSocketLog(PROC, "No response received. (" + socketErrorCode.ToString() + ")");
                }
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }

            return(result);
        }
Example #7
0
 public void SocketMessage(SocketError error)
 {
     if (error != SocketError.Success)
     {
         new _Message().Error(error.ToString());
     }
 }
 private void ServerTransactionFailed(SIPTransaction sipTransaction, SocketError failureReason)
 {
     if (!m_callCancelled)
     {
         CallFailed?.Invoke(this, failureReason.ToString(), null);
     }
 }
Example #9
0
        private void Login_NetClient_Disconnected(object sender, SocketError e)
        {
            Log.Warn("Disconnected (login socket)!");

            if (e > 0)
            {
                Characters = null;
                Servers    = null;

                if (Settings.GlobalSettings.Reconnect)
                {
                    Reconnect = true;

                    PopupMessage = string.Format
                                   (
                        ResGeneral.ReconnectPleaseWait01, _reconnectTryCounter,
                        StringHelper.AddSpaceBeforeCapital(e.ToString())
                                   );

                    UIManager.GetGump <LoadingGump>()?.SetText(PopupMessage);
                }
                else
                {
                    PopupMessage = string.Format
                                       (ResGeneral.ConnectionLost0, StringHelper.AddSpaceBeforeCapital(e.ToString()));
                }

                CurrentLoginStep = LoginSteps.PopUpMessage;
            }
        }
Example #10
0
    void ProcessError(SocketError error, bool acitve)
    {
        switch (error)
        {
        case SocketError.TimedOut:
        case SocketError.ConnectionRefused:
            events_.Add(NetEventID.OnTimeOut);
            break;

        case SocketError.NotConnected:
        case SocketError.ConnectionReset:
        case SocketError.ConnectionAborted:
            events_.Add(NetEventID.OnDisconnect);
            break;

        case SocketError.NetworkUnreachable:
            events_.Add(NetEventID.NetworkUnreachable);
            break;

        default: {
            Debug.LogError("ProcessError " + error.ToString());
        }
        break;
        }
    }
Example #11
0
        private static bool receiveFromSocket(ref byte[] outBuf, ref int offset, ref int count)
        {
            if (!isValid())
            {
                return(false);
            }
            SocketError error = mSocketClient.Receive(ref outBuf, ref offset, ref count);

            if (error != ((SocketError)((int)SocketError.Success)))
            {
                Log.e("Network", "longconn.Socket error in receive: " + error.ToString());
            }
            if ((error == ((SocketError)((int)SocketError.ConnectionAborted))) || (error == ((SocketError)((int)SocketError.ConnectionReset))))
            {
                Log.e("Network", "longconn.Socket closeed ");
                close();
                return(false);
            }
            if ((error != ((SocketError)((int)SocketError.Success))) || (count == 0))
            {
                return(false);
            }
            mSendFailedCount = 0;
            setAvailable(true);
            HostService.mLongConnHosts.onCurrentHostSuccess();
            return(true);
        }
Example #12
0
        private void ReceiveData(IntPtr socket)
        {
            PerIoData perIoData    = new PerIoData();
            GCHandle  gchPerIoData = GCHandle.Alloc(perIoData, GCHandleType.Pinned);

            Overlapped overlapped = new Overlapped();

            overlapped.mGCHPerIoData = gchPerIoData;
            perIoData.mGCHOverlapped = GCHandle.Alloc(overlapped, GCHandleType.Pinned);

            byte[] buffer = new byte[BUF_SIZE];
            perIoData.mGCHBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);

            perIoData.mWSABuffer.mLength  = BUF_SIZE;
            perIoData.mWSABuffer.mPointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
            perIoData.mType = OperationType.OT_RECEIVE;

            int         recvByte    = 0;
            SocketFlags socketFlags = SocketFlags.None;
            SocketError result      = WSARecv(socket, ref perIoData.mWSABuffer, 1, out recvByte, ref socketFlags, perIoData.mGCHOverlapped.AddrOfPinnedObject(), IntPtr.Zero);

            if (result != SocketError.SocketError && result != SocketError.Success && result != SocketError.IOPending)
            {
                Console.WriteLine("WSARecv Error! : " + result.ToString() + WSAGetLastError());
            }
        }
Example #13
0
        private void cbSendComplete(IAsyncResult result)
        {
            var r = result.AsyncState as Socket;

            if (r == null)
            {
                throw new InvalidOperationException("Invalid IAsyncResult - Could not interpret as a socket object");
            }
            SocketError err = new SocketError();

            r.EndSend(result, out err);
            if (err != SocketError.Success)
            {
                Console.WriteLine("Send Error" + err.ToString());
                Action doDCHost = new Action(DisconnectByHost);
                doDCHost.Invoke();
            }
            else
            {
                lock (SyncLock)
                {
                    tmrSendTimeout.Stop();
                }
            }
        }
Example #14
0
        /// <summary>
        /// 发送数据回调
        /// </summary>
        /// <param name="ar"></param>
        private void SendCallBack(IAsyncResult ar)
        {
            Debug.Log("sendCallBack");
            Socket      socket      = (Socket)ar.AsyncState;
            SocketError socketError = SocketError.Success;
            int         num         = 0;

            try
            {
                num = socket.EndSend(ar, out socketError);
                Debug.Log(num);
            }
            catch (Exception ex)
            {
                this.m_oNetwork.GetLogger().LogError("Exception occured on EndSend: " + ex.Message);
                this.Close();
                this.GetNetwork().PushClosedEvent(NetErrCode.Net_SysError);
                return;
            }
            if (socketError != SocketError.Success)
            {
                this.m_oNetwork.GetLogger().LogError("EndSend Error: " + socketError.ToString());
                this.Close();
                this.GetNetwork().PushClosedEvent(NetErrCode.Net_SysError);
            }
            else
            {
                this.m_nStartPos = (this.m_nStartPos + num) % this.m_oSendBuff.Length;//下次开始位置指针,也就是start+num(上次发送的长度)
                this.BeginSendData();
            }
        }
Example #15
0
        // Start asynchronous receiving binary data
        private void StartReceive()
        {
            Log.Add("client[" + this.id + "] connected");
            //Log.Add("client[" + this.id + "] started");
            try {
                SocketError error = SocketError.Fault;

                bool stop = false;
                //lock(this.locker) {
                if (this.socket != null && this.socket.Connected)
                {
                    this.socket.BeginReceive(this.buffer, 0, this.buffer.Length, SocketFlags.None, out error, OnReceive, null);
                }
                else
                {
                    stop = true;
                }
                //}
                if (stop)
                {
                    Log.Add("client[" + this.id + "] StartReceive, stop");
                    this.Stop();
                }

                if (error != SocketError.Success)
                {
                    Log.Add("client[" + this.id + "] StartReceive error: " + error.ToString());
                }
            } catch (SocketException exception) {
                Log.Add("client[" + this.id + "] StartReceive exception: " + exception.ToString());
            }
        }
Example #16
0
 /// <summary>
 /// 错误判断
 /// </summary>
 /// <param name="socketError"></param>
 /// <returns></returns>
 internal bool CheckSocketError(SocketError socketError)
 {
     switch ((socketError))
     {
     case SocketError.SocketError:
     case SocketError.VersionNotSupported:
     case SocketError.TryAgain:
     case SocketError.ProtocolFamilyNotSupported:
     case SocketError.ConnectionAborted:
     case SocketError.ConnectionRefused:
     case SocketError.ConnectionReset:
     case SocketError.Disconnecting:
     case SocketError.HostDown:
     case SocketError.HostNotFound:
     case SocketError.HostUnreachable:
     case SocketError.NetworkDown:
     case SocketError.NetworkReset:
     case SocketError.NetworkUnreachable:
     case SocketError.NoData:
     case SocketError.OperationAborted:
     case SocketError.Shutdown:
     case SocketError.SystemNotReady:
     case SocketError.TooManyOpenSockets:
         this.Close(socketError.ToString());
         return(true);
     }
     return(false);
 }
        /// <summary>
        /// Gets called when a receive operation resolves.  If we were listening for data and the connection
        /// closed, that also counts as a receive operation resolving.
        /// </summary>
        /// <param name="args"></param>
        private void OnReceiveResolved(bool isUDP, byte[] buffer, int bytesReceived, SocketError status, SockState sockState)
        {
            SocketDebug(19);
            //// Log.LogMsg("==>++++ Async RECEIVE Op Completed - #" + ((SockState)args.UserToken).ID.ToString() + "#");
            try
            {
                if (!OwningConnection.IsAlive && bytesReceived > 0)
                {
                    SocketDebug(20);
                    return;
                }

                SocketDebug(21);
                // If there was a socket error, close the connection. This is NOT a normal
                // situation, if you get an error here.
                if (status != SocketError.Success)
                {
                    SocketDebug(22);
                    Log.LogMsg("Receive status = " + status.ToString());
                    if (!OwningConnection.ShuttingDown)
                    {
                        //// Log.LogMsg("Testy 111");
                        OwningConnection.KillConnection("Connection lost! Network receive error: " + status);
                    }
                    //Jump out of the ProcessReceive method.
                    SocketDebug(23);
                    return;
                }

                SocketDebug(24);
                m_TCPSockState.AsyncEventArgs.RemoteEndPoint = OwningConnection.MyTCPSocket.RemoteEndPoint;

                // If no data was received, close the connection. This is a NORMAL
                // situation that shows when the client has finished sending data.
                if (bytesReceived == 0)
                {
                    SocketDebug(25);
                    if (!OwningConnection.ShuttingDown)
                    {
                        //// Log.LogMsg("Testy 114");
                        OwningConnection.KillConnection("Connection closed by remote host.");
                    }
                    return;
                }

                SocketDebug(26);
                OwningConnection.ReceivedBytes(bytesReceived);

                // restart listening process
                SocketDebug(27);
                OwningConnection.AssembleInboundPacket(buffer, bytesReceived, sockState);
                SocketDebug(28);
            }
            catch (Exception ex)
            {
                Log.LogMsg("Error ProcessReceive. " + ex.Message);
                OwningConnection.KillConnection("Error receive. " + ex.Message);
            }
        }
Example #18
0
        internal virtual void OnChannelError(string errorInfo, SocketError error)
        {
            GeneralEventArgs evt     = new GeneralEventArgs(ClientEvent.IO_ERROR);
            string           message = errorInfo + " : " + error.ToString();

            evt.ErrorDes = message;
            evt.Parame   = message;
            base.Dispatch(evt);
        }
Example #19
0
        public void SendNetStream(byte[] msg, int offset, int Length)
        {
            SocketError mError = SocketError.SocketError;

            try {
                mSocket.Send(msg, offset, Length, SocketFlags.None, out mError);
            } catch (Exception e) {
                DebugSystem.LogError("发送字节失败: " + e.Message + " | " + mError.ToString());
            }
        }
Example #20
0
 /// <summary>
 /// Initializes the websocket connection.
 /// </summary>
 public void Init()
 {
     this._webSocketServer.ListenerSocket.NoDelay = true;
     this._webSocketServer.Start(ConnectingSocket =>
     {
         ConnectingSocket.OnOpen    = () => this.OnSocketAdd(ConnectingSocket);
         ConnectingSocket.OnClose   = () => this.OnSocketRemove(ConnectingSocket);
         ConnectingSocket.OnMessage = SocketData => this.OnSocketMessage(ConnectingSocket, SocketData);
         ConnectingSocket.OnError   = SocketError => this.OnSocketError(SocketError.ToString());
     });
 }
Example #21
0
        /* Delegate method to be called upon connecting to an AI server asynchronously.
         * Params: IAsyncResult: */
        public static void connectCallback(IAsyncResult ar)
        {
            try {
                Socket clientState = (Socket)ar.AsyncState;
                // Complete connection
                clientState.EndConnect(ar);
                Debug.Log("Completed TCP connection to localhost on outPort (default 4999)");
                connectedSignal.Set();
            } catch (Exception unexpected) {
                if (unexpected is ObjectDisposedException)
                {
                    Debug.Log("Socket has been closed");
                }
                else if (unexpected is InvalidOperationException)
                {
                    Debug.Log("EndConnect was previously called for the asynchronous connection.");
                }
                else if (unexpected is SocketException)
                {
                    SocketError errcode = (SocketError)((SocketException)unexpected).ErrorCode;
                    switch (errcode)
                    {
                    case (SocketError.AccessDenied):
                        Debug.Log("Access Denied to socket");
                        break;

                    case (SocketError.ConnectionRefused):
                        Debug.Log("Connection Refused: Remote host refusing connection");
                        break;

                    case (SocketError.ConnectionReset):
                        Debug.Log("Connection Reset");
                        break;

                    case (SocketError.HostUnreachable):
                        Debug.Log("Host Unreachable: No route to remote host");
                        break;

                    case (SocketError.NetworkUnreachable):
                        Debug.Log("Network Unreachable: No route to remote host");
                        break;

                    default:
                        Debug.Log("Socket Error. Error Code: " + errcode.ToString());
                        break;
                    }
                }
                else
                {
                    Debug.Log("Unexpected Error");
                    Debug.Log(unexpected);
                }
            }
        }
Example #22
0
        protected bool SocketErrors()
        {
            if (sockErr == SocketError.Success)
            {
                return(false);
            }

            WriteError("IFO:     Socket Error: {0}", sockErr.ToString());
            Disconnect();
            return(true);
        }
Example #23
0
 }                                                       // Current packet length
 /// <summary>
 /// Throw an exception if an send error is reported.The error can either
 /// be because the errorReported boolean is true or an actual socket error
 /// reported has been reported by the system.
 /// </summary>
 /// <param name="errorReported"></param>
 /// <param name="socketError"></param>
 void ThrowOnError(bool errorReported, SocketError socketError)
 {
     if (errorReported || socketError != SocketError.Success)
     {
         string errorMessage = ("Connection to remote peer has been closed down.");
         if (socketError != SocketError.Success)
         {
             errorMessage += "Socket Error: " + socketError.ToString();
         }
         throw new Exception(errorMessage);
     }
 }
 public void OnMyConnected(Connection connection, SocketError result)
 {
     LogU.Debug("Connect ProxyServer: {0}", result);
     if (result == SocketError.Success)
     {
         clientCore.transmitter.Connection = connection;
     }
     else
     {
         LogU.Debug("Connect ProxyServer Faild !!! :{0}", result.ToString("X"));
     }
 }
Example #25
0
        static public void ProcessSocketClient(Socket client)
        {
            IntPtr      socketHandle = client.Handle;
            SocketError socketErr    = SocketError.Success;

            while (client.Connected)
            {
                byte[] buffer = new byte[4096];
                int    recLen = 0;
                try
                {
                    recLen = client.Receive(buffer, buffer.Length, SocketFlags.None);
                }
                catch (SocketException se)
                {
                    socketErr = se.SocketErrorCode;
                    break;
                }
                System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                string requestString      = utf8.GetString(buffer, 0, recLen);

                string msg = string.Format("时间:{0}\r\n接收信息:{1}\r\n", DateTime.Now.ToString(), requestString);
                Console.WriteLine("客户端: " + client.Handle);
                Console.WriteLine(msg);
                Console.WriteLine("");

                try
                {
                    client.Send(utf8.GetBytes(msg));
                }
                catch (SocketException se)
                {
                    socketErr = se.SocketErrorCode;
                    break;
                }


                if (Console.KeyAvailable)
                {
                    break;
                }
            }
            Console.WriteLine("客户端[{0}]连接断开,{1}", socketHandle, socketErr.ToString());

            /*
             * for (int i = 0; i < 10; i++)
             * {
             *  client.Send(System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString() + "\r\n"));
             *  Thread.Sleep(1000);
             * }
             */
        }
 bool ShouldRetryAccept(SocketError error)
 {
     if (error == SocketError.OperationAborted)
     {
         // Close/Abort was called
         return(false);
     }
     else
     {
         AmqpTrace.Provider.AmqpListenSocketAcceptError(this, true, error.ToString());
         return(true);
     }
 }
Example #27
0
        public override string ToString()
        {
            if (Error != null)
            {
                return(Error);
            }

            if (Exception != null)
            {
                return(Exception.ToString());
            }

            return(@"SocketError :" + SocketError.ToString());
        }
Example #28
0
 private void OnConnectServer(SocketError error)
 {
     MotionLog.Log($"Server connect result : {error}");
     if (error == SocketError.Success)
     {
         States = ENetworkStates.Connected;
         NetworkEventDispatcher.SendConnectSuccessMsg();
     }
     else
     {
         States = ENetworkStates.Disconnect;
         NetworkEventDispatcher.SendConnectFailMsg(error.ToString());
     }
 }
Example #29
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);
        }
Example #30
0
        static public void ProcessSocketClient(Socket client)
        {
            IntPtr      socketHandle = client.Handle;
            SocketError socketErr    = SocketError.Success;

            try
            {
                while (client.Connected)
                {
                    byte[] buffer = new byte[4096];
                    int    recLen = 0;
                    try
                    {
                        recLen = client.Receive(buffer, buffer.Length, SocketFlags.None);
                    }
                    catch (SocketException se)
                    {
                        socketErr = se.SocketErrorCode;
                        break;
                    }
                    System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                    string requestString      = utf8.GetString(buffer, 0, recLen);

                    //string msg = string.Format("时间:{0}\r\n接收信息:{1}\r\n", DateTime.Now.ToString(), requestString);
                    string msg = requestString;
                    Console.WriteLine("客户端: " + client.Handle);
                    Console.WriteLine(msg);
                    Console.WriteLine("");

                    LogServiceMessage(string.Format("客户端: {0}\r\n{1}\r\n", client.Handle, msg));


                    try
                    {
                        client.Send(utf8.GetBytes(msg));
                    }
                    catch (SocketException se)
                    {
                        socketErr = se.SocketErrorCode;
                        break;
                    }
                }
                Console.WriteLine("客户端[{0}]连接断开,{1}", socketHandle, socketErr.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("连接出现异常:{0}", e.Message));
            }
        }
Example #31
0
 private void OnSocketError(string message, SocketError se)
 {
     this.manualDisconnection = false;
     if (this.attemptingReconnection)
     {
         this.Reconnect();
     }
     else
     {
         BitSwarmEvent bitSwarmEvent = new BitSwarmEvent(BitSwarmEvent.IO_ERROR);
         bitSwarmEvent.Params            = new Hashtable();
         bitSwarmEvent.Params["message"] = message + " ==> " + se.ToString();
         this.DispatchEvent(bitSwarmEvent);
     }
 }
        // 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)
        {
            GlobalLog.Print(
                "BaseOverlappedAsyncResult#" + LoggingHash.HashString(this) +
                "::CheckAsyncCallOverlappedResult(" + errorCode.ToString() + ")");

            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;
        }
Example #33
0
        public static NetMQException Create(SocketError error, [CanBeNull] Exception innerException = null)
        {
            ErrorCode errorCode;

            switch (error)
            {
                case SocketError.AccessDenied:
                    errorCode = ErrorCode.AccessDenied;
                    break;
                case SocketError.Fault:
                    errorCode = ErrorCode.Fault;
                    break;
                case SocketError.InvalidArgument:
                    errorCode = ErrorCode.Invalid;
                    break;
                case SocketError.TooManyOpenSockets:
                    errorCode = ErrorCode.TooManyOpenSockets;
                    break;
                case SocketError.InProgress:
                    errorCode = ErrorCode.TryAgain;
                    break;
                case SocketError.MessageSize:
                    errorCode = ErrorCode.MessageSize;
                    break;
                case SocketError.ProtocolNotSupported:
                    errorCode = ErrorCode.ProtocolNotSupported;
                    break;
                case SocketError.AddressFamilyNotSupported:
                    errorCode = ErrorCode.AddressFamilyNotSupported;
                    break;
                case SocketError.AddressNotAvailable:
                    errorCode = ErrorCode.AddressNotAvailable;
                    break;
                case SocketError.NetworkDown:
                    errorCode = ErrorCode.NetworkDown;
                    break;
                case SocketError.NetworkUnreachable:
                    errorCode = ErrorCode.NetworkUnreachable;
                    break;
                case SocketError.NetworkReset:
                    errorCode = ErrorCode.NetworkReset;
                    break;
                case SocketError.ConnectionAborted:
                    errorCode = ErrorCode.ConnectionAborted;
                    break;
                case SocketError.ConnectionReset:
                    errorCode = ErrorCode.ConnectionReset;
                    break;
                case SocketError.NoBufferSpaceAvailable:
                    errorCode = ErrorCode.NoBufferSpaceAvailable;
                    break;
                case SocketError.NotConnected:
                    errorCode = ErrorCode.NotConnected;
                    break;
                case SocketError.TimedOut:
                    errorCode = ErrorCode.TimedOut;
                    break;
                case SocketError.ConnectionRefused:
                    errorCode = ErrorCode.ConnectionRefused;
                    break;
                case SocketError.HostUnreachable:
                    errorCode = ErrorCode.HostUnreachable;
                    break;
                default:
                    errorCode = 0; // to indicate no valid SocketError.
            #if DEBUG
                    string s = string.Format("(And within NetMQException.Create: Unanticipated error-code: {0})", error.ToString());
                    return Create(errorCode: errorCode, message: s, innerException: innerException);
            #else
                    break;
            #endif
            }

            return Create(errorCode, innerException);
        }
Example #34
0
        internal void UpdateStatusAfterSocketError(SocketError errorCode)
        {
            // If we already know the socket is disconnected
            // we don't need to do anything else.
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::UpdateStatusAfterSocketError(socketException)");
            }

            if (s_loggingEnabled)
            {
                NetEventSource.PrintError(NetEventSource.ComponentType.Socket, this, nameof(UpdateStatusAfterSocketError), errorCode.ToString());
            }

            if (_isConnected && (_handle.IsInvalid || (errorCode != SocketError.WouldBlock &&
                    errorCode != SocketError.IOPending && errorCode != SocketError.NoBufferSpaceAvailable &&
                    errorCode != SocketError.TimedOut)))
            {
                // The socket is no longer a valid socket.
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("Socket#" + LoggingHash.HashString(this) + "::UpdateStatusAfterSocketError(socketException) Invalidating socket.");
                }

                SetToDisconnected();
            }
        }
Example #35
0
 bool ShouldRetryAccept(SocketError error)
 {
     if (error == SocketError.OperationAborted)
     {
         // Close/Abort was called
         return false;
     }
     else
     {
         AmqpTrace.Provider.AmqpListenSocketAcceptError(this, true, error.ToString());
         return true;
     }
 }
Example #36
0
        public static NetMQException Create(SocketError error, [CanBeNull] Exception innerException = null)
        {
            var errorCode = error.ToErrorCode();

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

            return Create(errorCode, innerException);
        }
Example #37
0
        internal void UpdateStatusAfterSocketError(SocketError errorCode)
        {
            // If we already know the socket is disconnected
            // we don't need to do anything else.
            GlobalLog.Print("Socket#" + Logging.HashString(this) + "::UpdateStatusAfterSocketError(socketException)");
            if (s_loggingEnabled)
            {
                Logging.PrintError(Logging.Sockets, this, "UpdateStatusAfterSocketError", errorCode.ToString());
            }

            if (_isConnected && (_handle.IsInvalid || (errorCode != SocketError.WouldBlock &&
                    errorCode != SocketError.IOPending && errorCode != SocketError.NoBufferSpaceAvailable &&
                    errorCode != SocketError.TimedOut)))
            {
                // The socket is no longer a valid socket.
                GlobalLog.Print("Socket#" + Logging.HashString(this) + "::UpdateStatusAfterSocketError(socketException) Invalidating socket.");
                SetToDisconnected();
            }
        }
Example #38
0
        private void ProcessSocketError(Socket socket, SocketError socketError)
        {
            if (socketError == SocketError.Success)
            {
                // No problems here
                return;
            }

            if (socketError == SocketError.ConnectionReset)  // disconnect
            {
                if (this.RemoteDisconnect != null)
                {
                    this.RemoteDisconnect(socket, EventArgs.Empty);
                    return;  // That's all we need to do
                }
            }

            if (this.UnhandledSocketError != null)
            {
                this.UnhandledSocketError(socket, socketError);
                return;
            }

            Console.WriteLine(string.Format("Socket error: {0}", socketError.ToString()));

 //           throw new CommunicationException("Socket error: " + socketError.ToString(), new SocketException());
        }
        /// <summary>
        /// Gets called when a receive operation resolves.  If we were listening for data and the connection
        /// closed, that also counts as a receive operation resolving.
        /// </summary>
        /// <param name="args"></param>
        private void OnReceiveResolved(bool isUDP, byte[] buffer, int bytesReceived, SocketError status, SockState sockState)
        {
            SocketDebug(19);
            //// Log.LogMsg("==>++++ Async RECEIVE Op Completed - #" + ((SockState)args.UserToken).ID.ToString() + "#");
            try
            {
                if (!OwningConnection.IsAlive && bytesReceived > 0)
                {
                    SocketDebug(20);
                    return;
                }

                SocketDebug(21);
                // If there was a socket error, close the connection. This is NOT a normal
                // situation, if you get an error here.
                if (status != SocketError.Success)
                {
                    SocketDebug(22);
                    Log.LogMsg("Receive status = " + status.ToString());
                    if (!OwningConnection.ShuttingDown)
                    {
                        //// Log.LogMsg("Testy 111");
                        OwningConnection.KillConnection("Connection lost! Network receive error: " + status);
                    }
                    //Jump out of the ProcessReceive method.
                    SocketDebug(23);
                    return;
                }

                SocketDebug(24);
                m_TCPSockState.AsyncEventArgs.RemoteEndPoint = OwningConnection.MyTCPSocket.RemoteEndPoint;

                // If no data was received, close the connection. This is a NORMAL
                // situation that shows when the client has finished sending data.
                if (bytesReceived == 0)
                {
                    SocketDebug(25);
                    if (!OwningConnection.ShuttingDown)
                    {
                        //// Log.LogMsg("Testy 114");
                        OwningConnection.KillConnection("Connection closed by remote host.");
                    }
                    return;
                }

                SocketDebug(26);
                OwningConnection.ReceivedBytes(bytesReceived);

                // restart listening process
                SocketDebug(27);
                OwningConnection.AssembleInboundPacket(buffer, bytesReceived, sockState);
                SocketDebug(28);
            }
            catch (Exception ex)
            {
                Log.LogMsg("Error ProcessReceive. " + ex.Message);
                OwningConnection.KillConnection("Error receive. " + ex.Message);
            }
        }