Example #1
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="type">消息类型,参见枚举MessageType</param>
        /// <param name="to">要接收消息的用户</param>
        /// <param name="group">要接收消息的组</param>
        /// <param name="data">附加数据</param>
        /// <param name="callback">回调</param>
        /// <returns>消息ID</returns>
        public string Send(MessageType type, string to, string group, object data, Action <RequestInfo, ResponseAckInfo> callback)
        {
            var requestInfo = new Message.RequestInfo()
            {
                MsgType = type,
                //MessageId = TimeStamp.Create(),
                ToId     = to,
                GroupId  = group,
                Data     = data,
                Callback = callback
            };
            var preRequestInfo = new Message.RequestInfo()
            {
                MsgType = type,
                //MessageId = TimeStamp.Create(),
                ToId     = to,
                GroupId  = group,
                Data     = data,
                Callback = callback
            };

            LogOpInfo("Send", requestInfo.ToJsonString());

            //连接不可用
            if (!IsAvailable)
            {
                RunUserCallback(callback, requestInfo, new ResponseAckInfo()
                {
                    MessageId = requestInfo.MessageId, MsgType = MessageType.Ack, Status = ResponseCode.NO_AUTH
                });
                return(requestInfo.MessageId);
            }

            if (!Permission.CheckPermission(m_User, type))
            {
                RunUserCallback(callback, requestInfo, new ResponseAckInfo()
                {
                    MessageId = requestInfo.MessageId, MsgType = MessageType.Ack, Status = ResponseCode.NO_PERMISSION
                });
                return(requestInfo.MessageId);
            }

            //深拷贝到请求列表中
            m_SendBuffer.TryAdd(requestInfo.MessageId, new RequestInfo()
            {
                MessageId      = requestInfo.MessageId,
                Callback       = requestInfo.Callback,
                Data           = requestInfo.Data,
                MsgType        = requestInfo.MsgType,
                RelateFileInfo = requestInfo.RelateFileInfo,
                ToId           = requestInfo.ToId,
                Version        = requestInfo.Version,
                GroupId        = requestInfo.GroupId
            });

            if (EnableEncrypt)
            {
                requestInfo.Data = EncryptAdapter.Encode(CommonExt.DynamicToJsonString(requestInfo.Data), requestInfo);
                LogOpInfo("Send--AfterEncode", requestInfo.ToJsonString());
            }
            try
            {
                byte[] sendData = requestInfo.ToByte <Message.RequestInfo>();

                m_Client.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, null, m_Client);

                UpdateTimeForInitiativePing();
            }
            catch (Exception ex)
            {
                ProcessError(requestInfo.MessageId, ex);
                RunUserCallback(callback, preRequestInfo, new ResponseAckInfo()
                {
                    MessageId = requestInfo.MessageId, MsgType = MessageType.Ack, Status = ResponseCode.TIMEOUT
                });
            }

            return(requestInfo.MessageId);
        }
Example #2
0
        /// <summary>
        /// 打开连接
        /// </summary>
        /// <param name="host">服务器地址</param>
        /// <param name="port">服务器端口号</param>
        /// <param name="userType">用户类型</param>
        /// <param name="userName">用户显示的名称</param>
        /// <param name="userAgent">用户登陆的终端信息</param>
        /// <param name="accessToken">访问令牌</param>
        /// <param name="lastTick">收到最后一条消息的UNIX时间戳</param>
        /// <param name="callback">回调函数</param>
        /// <returns>连接是否成功</returns>
        public bool Connect(string host, int port, string userType, string userName, string userAgent, string accessToken, int lastTick, Action <RequestInfo, ResponseAckInfo> callback)
        {
            var requestInfo = new Message.RequestInfo()
            {
                MsgType = MessageType.Connect,
                //MessageId = TimeStamp.Create(),
                Data = new
                {
                    userType    = userType,
                    userName    = userName,
                    userAgent   = userAgent,
                    accessToken = accessToken,
                    lastTick    = lastTick
                },
                Version = Encrypt_Version
            };
            var preRequestInfo = new Message.RequestInfo()
            {
                MsgType = MessageType.Connect,
                Data    = requestInfo.Data,
                Version = Encrypt_Version
            };

            if (IsAvailable)
            {
                //已经连接成功
                if (callback != null)
                {
                    callback(requestInfo, new ResponseAckInfo()
                    {
                        MsgType = MessageType.Ack, Status = ResponseCode.OK
                    });
                }
                return(true);
            }
            bool result = false;

            //开始连接
            try
            {
                m_Client = new Socket(SocketType.Stream, ProtocolType.Tcp);

                if (EnableEncrypt)
                {
                    requestInfo.Data = EncryptAdapter.Encode(CommonExt.DynamicToJsonString(requestInfo.Data), requestInfo);
                }

                LogOpInfo("BeginConnect:", requestInfo.ToJsonString());
                m_Client.Connect(host, port);
                m_IpAddress = host;
                m_Port      = port;
                if (m_Client.Connected)
                {
                    byte[] sendData = requestInfo.ToByte <Message.RequestInfo>();

                    m_Client.Send(sendData);
                    byte[] bufferData   = new byte[BufferSize];
                    int    receiveLen   = m_Client.Receive(bufferData);
                    byte[] receivedData = bufferData.ToList().GetRange(0, receiveLen).ToArray();
                    var    responseInfo = receivedData.ToObject <Message.ResponseAckInfo>();
                    if (EnableEncrypt)
                    {
                        dynamic deString = CommonCryptoService.Decrypt_DES(responseInfo.Data.ToString(), responseInfo.MessageId);
                        responseInfo.Data = CommonExt.JsonStringToDynamic(deString.ToString());
                    }
                    //LogOpInfo("ConnectOver:", responseInfo.ToJsonString());
                    if (responseInfo.Status == ResponseCode.OK)
                    {
                        m_User.IsAuthenticated    = true;
                        m_User.Name               = userName;
                        m_User.Token              = accessToken;
                        m_User.UserAgent          = userAgent;
                        m_User.UserType           = userType;
                        m_User.AuthenticationType = responseInfo.Data.userPermission;
                        m_User.PermissionList     = Permission.GetUserPermission(m_User.AuthenticationType);
                        //连接使用同步
                        // _sendBuffer.Add(requestInfo);
                        m_LastPingTime = DateTime.Now;

                        //启动线程接收
                        AfterConnectedServer();
                        result            = true;
                        m_IsCanConnecting = true;

                        if (this.clientPingMode == PingMode.Initiative)
                        {
                            _lastSendTime = DateTime.Now;
                            PingTimer.Start();
                        }
                    }
                    else
                    {
                        m_Client.Disconnect(true);
                    }

                    RunUserCallback(callback, preRequestInfo, responseInfo);
                }
            }
            catch (Exception ex)
            {
                LogInfo("ConnectError", ex);
                RunUserCallback(callback, preRequestInfo, new ResponseAckInfo()
                {
                    MsgType = MessageType.Ack, Status = ResponseCode.CLINET_ERR, Data = ex.Message
                });
            }

            return(result);
        }