コード例 #1
0
    /// <summary>
    /// 循环检测连接状态,监测发送队列是否为空并发送消息
    /// </summary>
    /// <returns></returns>
    IEnumerator OnSendMessage()
    {
        while (true)
        {
            yield return(new WaitForEndOfFrame()); /*Yielders.EndOfFrame;*/

            if (IsConnected())
            {
                if (_sendBuffer.ReadPosition < _sendBuffer.WritePosition)
                {
                    try
                    {
                        int sent = _socket.Send(_sendBuffer.Buffer, _sendBuffer.ReadPosition, (_sendBuffer.WritePosition - _sendBuffer.ReadPosition), SocketFlags.None);
                        if (sent >= 0)
                        {
                            _sendBuffer.AddReadPosition(sent);
                        }
                        else
                        {
                            throw new Exception("Socket sent return " + sent);
                        }
                    }
                    catch (Exception e)
                    {
                        int errorCode = 0;
                        if (e is SocketException)
                        {
                            errorCode = (e as SocketException).ErrorCode;
                        }
                        Debug.LogWarning("!!!Socket send error Error msg: " + e.Message + "  |||Error code:" + errorCode);
                        SetReConnectStatus();
                    }
                }
            }
            else
            {
                if (currentStatus == ConnectStatus.CONNECTED)
                {
                    Debug.LogWarning("Socket send Reconnect!!!!!");
                    SetReConnectStatus();
                }
            }
        }
    }