예제 #1
0
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="sendbuffer">消息体</param>
        public void Send(byte[] sendbuffer)
        {
            if (!Connected)
            {
                throw new SocketException((Int32)SocketError.NotConnected);
            }

            if (GetSendMessage == null)
            {
                throw new ArgumentException("The function GetSendMessage can not be null!");
            }

            if (sendbuffer.Length == 0)
            {
                return;
            }

            MySocketAsyncEventArgs senderSocketAsyncEventArgs = senderSocketAsyncEventArgsList.Find(q => q.State == 0);

            if (senderSocketAsyncEventArgs == null)
            {
                senderSocketAsyncEventArgs = InitSendArg();
            }

            lock (senderSocketAsyncEventArgs)
            {
                senderSocketAsyncEventArgs.State = 1;

                senderSocketAsyncEventArgs.SetBuffer(sendbuffer, 0, sendbuffer.Length);
            }

            clientSocket.SendAsync(senderSocketAsyncEventArgs);
        }
예제 #2
0
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="uid">要发送的用户的uid</param>
        /// <param name="msg">消息体</param>
        public void Send(string uid, byte[] sendbuffer)
        {
            if (string.IsNullOrEmpty(uid) || sendbuffer.Length == 0)
            {
                return;
            }

            SocketAsyncEventArgsWithId socketWithId = readWritePool.FindByUID(uid);

            if (socketWithId == null)
            {
                OnSended(null, SocketError.NotSocket); return;
            }

            MySocketAsyncEventArgs e = socketWithId.SendSAEA;

            AsyncUserToken token = (AsyncUserToken)e.UserToken;

            token.FreshTime = DateTime.Now;

            if (e.SocketError != SocketError.Success)
            {
                OnSended(token, e.SocketError);
                this.CloseClientSocket(e.UID);
                return;
            }

            int i = 0;

            try
            {
                e.SetBuffer(sendbuffer, 0, sendbuffer.Length);

                if (!token.Socket.SendAsync(e))
                {
                    this.ProcessSend(e);
                }
            }
            catch (Exception)
            {
                if (i <= 5)
                {
                    i++;
                    //如果发送出现异常就延迟0.01秒再发
                    Thread.Sleep(10);
                    Send(uid, sendbuffer);
                }
                else
                {
                    OnSended(token, SocketError.SocketError);
                }
            }
        }