コード例 #1
0
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = (AsyncUserToken)e.UserToken;

            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                token.Process(e.Buffer, e.BytesTransferred);
                Receive(token);
            }
            else
            {
                CloseClientSocket(e);
            }
        }
コード例 #2
0
ファイル: AsyncIOCPServer.cs プロジェクト: lxc1030/ServerTest
    private void Init()
    {
        bufferManager = new BufferManager(maxClient * 4 * bufferSize, bufferSize);
        userTokenPool = new AsyncUserTokenPool(maxClient);
        for (int i = 0; i < maxClient; i++) //填充SocketAsyncEventArgs池
        {
            AsyncUserToken userToken = new AsyncUserToken(bufferSize);
            userToken.SAEA_Receive.UserToken  = userToken;
            userToken.SAEA_Receive.Completed += new EventHandler <SocketAsyncEventArgs>(OnIOCompleted);
            bufferManager.SetBuffer(userToken.SAEA_Receive);

            userTokenPool.Push(userToken);
        }
    }
コード例 #3
0
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            Interlocked.Increment(ref m_currentlyConnectedUsers);

            AsyncUserToken userToken = m_userTokens.GetObject();

            userToken.Socket = e.AcceptSocket;

            m_eventHandlers.OnUserConnect(userToken);

            Receive(userToken);

            StartAccept(e);
        }
コード例 #4
0
        private void Listener_OnMsgReceived(AsyncUserToken token, byte[] info)
        {
            string str = BytesUtil.ToHexString(info);

            try
            {
                RecieveMessageDecode reader  = new RecieveMessageDecode(info);
                RecieveMessage       message = reader.Read();

                StringBuilder sb = new StringBuilder();
                sb.Append("接收到数据:");
                sb.Append("\r\n");
                sb.Append(" 来源IP:" + token.Remote.Address.ToString());
                sb.Append("\r\n");
                sb.Append(" 接收时间:" + DateTime.Now);
                sb.Append("\r\n");
                sb.Append(" 数据类型:" + message.FunctionCode);
                sb.Append("\r\n");
                sb.Append(" 接收内容:" + str);
                sb.Append("\r\n");
                AppendLog(sb.ToString());

                //更新设备缓存
                UpdateCache(message.ClientCodeStr, token.UID);
                if (message.FunctionCode.Equals("F2"))
                {
                    return;
                }
                IMessageHandler handler = HandlerFactory.Create(message.FunctionCode, token.UID, message);
                handler.Handle();

                //如果是设备自报数据,向设备发送接收成功的报文
                if (message.FunctionCode.Equals("C0"))
                {
                    SendMessage res = new SendMessage();
                    res.ClientCode   = message.ClientCode;
                    res.CenterCode   = message.CenterCode;
                    res.SendTime     = DateTime.Now;
                    res.Serial       = 0;
                    res.FunctionCode = "C0";

                    listener.Send(token.UID, res.ToByte());
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("接收消息时出错", "接收到的消息:" + str + "\r\n" + ex.Message, ex.StackTrace);
            }
        }
コード例 #5
0
ファイル: SocketManager.cs プロジェクト: 287396159/WQWORK
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            try
            {
                Interlocked.Increment(ref m_clientCount);
                // Get the socket for the accepted client connection and put it into the
                //ReadEventArg object user token
                SocketAsyncEventArgs readEventArgs = m_pool.Pop();
                AsyncUserToken       userToken     = (AsyncUserToken)readEventArgs.UserToken;
                userToken.Socket      = e.AcceptSocket;
                userToken.ConnectTime = DateTime.Now;
                userToken.Remote      = e.AcceptSocket.RemoteEndPoint;
                if (userToken.Remote != null)
                {
                    userToken.IPAddress = ((IPEndPoint)(e.AcceptSocket.RemoteEndPoint)).Address;

                    Console.Write(userToken.IPAddress.ToString() + "已连接");
                    lock (m_clients) { m_clients.Add(userToken); }
                    lock (m_DicClients)
                    {
                        if (!m_DicClients.ContainsKey(userToken.Remote.ToString()))
                        {
                            m_DicClients.Add(userToken.Remote.ToString(), userToken);
                        }
                    }
                }

                if (ClientNumberChange != null)
                {
                    ClientNumberChange(1, userToken);
                }
                if (!e.AcceptSocket.ReceiveAsync(readEventArgs))
                {
                    ProcessReceive(readEventArgs);
                }
            }
            catch (Exception me)
            {
                Console.Write(me.Message + "\r\n" + me.StackTrace);
                //    RuncomLib.Log.LogUtils.Info(me.Message + "\r\n" + me.StackTrace);
            }

            // Accept the next connection request
            if (e.SocketError == SocketError.OperationAborted)
            {
                return;
            }
            StartAccept(e);
        }
コード例 #6
0
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArg)
        {
            try
            {
                if (acceptEventArg.AcceptSocket == null)
                {
                    return;
                }

                Interlocked.Increment(ref m_clientCount);

                IPEndPoint clientAddress = acceptEventArg.AcceptSocket.RemoteEndPoint as IPEndPoint;
                EndPoint   localEndPoint = acceptEventArg.AcceptSocket.LocalEndPoint;
                _logger.LogInformation($"{localEndPoint} <=> {clientAddress} 连接");

                SocketAsyncEventArgs readEventArgs = m_pool.Pop();
                AsyncUserToken       userToken     = (AsyncUserToken)readEventArgs.UserToken;
                userToken.Socket      = acceptEventArg.AcceptSocket;
                userToken.ConnectTime = DateTime.Now;
                userToken.Remote      = acceptEventArg.AcceptSocket.RemoteEndPoint;
                userToken.Local       = ((IPEndPoint)(acceptEventArg.AcceptSocket.LocalEndPoint)).Address;

                lock (m_clients) { m_clients.Add(userToken); }

                if (!acceptEventArg.AcceptSocket.ReceiveAsync(readEventArgs))
                {
                    ProcessReceive(readEventArgs);
                }

                //while (_stoppingToken.IsCancellationRequested == false)
                //{
                //    AsyncUserToken token = (AsyncUserToken)readEventArgs.UserToken;
                //    if (token.Stop) break;

                //    if (!token.Socket.ReceiveAsync(readEventArgs))
                //        ProcessReceive(readEventArgs);
                //}
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }

            if (acceptEventArg.SocketError == SocketError.OperationAborted)
            {
                return;
            }
            StartAccept(acceptEventArg);
        }
コード例 #7
0
ファイル: AppManager.cs プロジェクト: jiangboh/CS
 /// <summary>
 /// 重写设备更改事件
 /// </summary>
 /// <param name="num">num大于0表示设备上线,否则设备下线</param>
 /// <param name="appToKen">设备信息</param>
 public override void OnDeviceNumberChange(int num, AsyncUserToken appToKen)
 {
     if (num > 0)
     {
         //OnOutputLog(LogInfoType.EROR, string.Format("上上上线APP:[{0}:{1}]:", appToKen.IPAddress.ToString(),appToKen.Port));
         MyDeviceList.add(appToKen);
         //在收到心跳消息时上报
         //send2main_OnOffLine(OnLine,token);
     }
     else  //AP下线,删除设备列表中的AP信息
     {
         //OnOutputLog(LogInfoType.EROR, string.Format("下下下线APP:[{0}:{1}]:", appToKen.IPAddress.ToString(), appToKen.Port));
         MyDeviceList.remov(appToKen);
     }
 }
コード例 #8
0
ファイル: AsyncIOCPServer.cs プロジェクト: lxc1030/ServerTest
    private void XieYiThrd(object state)
    {
        object[]       all       = (object[])state;
        AsyncUserToken userToken = (AsyncUserToken)all[0];
        MessageXieYi   xieyi     = (MessageXieYi)all[1];



        //将接收到的数据经过处理再发送出去
        byte[] backInfo = ServerDataManager.instance.SelectMessage(xieyi, userToken); //判断逻辑
        if (backInfo != null)
        {
            SendSave(userToken, backInfo);
        }
    }
コード例 #9
0
        private void InitUserToken(int bufferSize)
        {
            var readEventArgs  = new SocketAsyncEventArgs();
            var writeEventArgs = new SocketAsyncEventArgs();

            readEventArgs.Completed  += IO_Completed;
            writeEventArgs.Completed += IO_Completed;

            byte[] buffer = new byte[bufferSize];
            readEventArgs.SetBuffer(buffer, 0, buffer.Length);

            m_userToken = new AsyncUserToken(readEventArgs, writeEventArgs);
            m_userToken.OnMessageError         = m_eventHandlingContainer.OnMessageError;
            m_userToken.OnMessageFullyReceived = m_eventHandlingContainer.OnMessageReceived;
        }
コード例 #10
0
    public byte[] UpdateName(AsyncUserToken userToken, string name)
    {
        string sql = SqlManager.instance.UpdateInto(
            TableName.register,
            nameof(Register.name), name,
            nameof(Register.userID), userToken.userInfo.Register.userID
            );
        int count = SqlManager.instance.DataWrite(sql);

        if (count > 0)
        {
            userToken.userInfo.Register.name = name;
        }
        return(SerializeHelper.Serialize <RoomActor>(userToken.userInfo));
    }
コード例 #11
0
        public void SuddenlyEndGameOnPlayerDisconnect(AsyncUserToken userToken)
        {
            ServerSideTokenIdentity identity = (ServerSideTokenIdentity)userToken.info;

            lock (identity.MatchmakingLock)
            {
                if (identity.MatchmakingStatus != UserMatchmakingStatus.GAME)
                {
                    return;
                }

                GameWrapper gameWrapper = identity.GameWrapper;

                var game = gameWrapper.Game;

                if (game.Players.Length != 2)
                {
                    // Only for 2 player games
                    return;
                }

                lock (gameWrapper.@lock)
                {
                    GameFinishedNotification gameFinishedNotification = new GameFinishedNotification();


                    for (int i = 0; i < gameWrapper.Tokens.Length; i++)
                    {
                        var token = gameWrapper.Tokens[i];
                        if (token == userToken)
                        {
                            gameFinishedNotification.WinnerPlayerId = 1 - i;
                            break;
                        }
                    }

                    foreach (var token in gameWrapper.Tokens)
                    {
                        if (token != userToken)
                        {
                            Config.GameServer.Send(token, gameFinishedNotification);
                        }
                    }

                    TerminateGame(gameWrapper);
                }
            }
        }
コード例 #12
0
    public void CheckQuit(AsyncUserToken userToken, QuitInfo quitInfo)
    {
        if (quitInfo.userIndex != 0 && quitInfo.userIndex != quitInfo.quitUnique)//不是房主,并且踢的也不是自己
        {
            Log4Debug("无权踢人");
            quitInfo.isQuit = false;
        }
        else
        {
            quitInfo.isQuit = Quit(quitInfo.quitUnique);
        }
        byte[]       message = SerializeHelper.Serialize <QuitInfo>(quitInfo);
        MessageXieYi xieyi   = new MessageXieYi((byte)MessageConvention.quitRoom, 0, message);

        AsyncIOCPServer.instance.SendSave(UserTokenInfo[quitInfo.quitUnique], xieyi.ToBytes());
    }
コード例 #13
0
ファイル: AppManager.cs プロジェクト: jiangboh/CS
        /// <summary>
        /// 发送通用出错消息给App
        /// </summary>
        /// <param name="appToKen">App信息</param>
        /// <param name="type">接收到的消息类型</param>
        /// <param name="str">出错信息描述</param>
        protected void SendErrorMsg2App(AsyncUserToken appToKen, AppMsgType type, String str)
        {
            string sType = string.Empty;

            if (type != null)
            {
                sType = type.ToString();
            }

            Msg_Body_Struct TypeKeyValue =
                new Msg_Body_Struct(AppMsgType.general_error_result,
                                    "ErrStr", str,
                                    "RecvType", sType);

            SendMsg2App(appToKen, TypeKeyValue);
        }
コード例 #14
0
ファイル: TCPSocketServer.cs プロジェクト: shuimo1008/Smlib
        protected bool OnSendAsync(SocketAsyncEventArgs eventArgs)
        {
            AsyncUserToken socketToken = eventArgs.UserToken as AsyncUserToken;

            socketToken.ActiveDateTime = DateTime.Now;

            if (eventArgs.SocketError == SocketError.Success)
            {
                return(socketToken.SendAsync(true)); //调用子类回调函数
            }
            else
            {
                CloseSocket(socketToken);
                return(false);
            }
        }
コード例 #15
0
        public IRemoteObject Handle(AsyncUserToken token, IRemoteObject remoteObject)
        {
            Dictionary <Type, RequestHandler> handleMapper = GetMapperDictionary();

            if (handleMapper == null)
            {
                throw new InvalidOperationException();
            }
            RequestHandler handler;

            if (handleMapper.TryGetValue(remoteObject.GetType(), out handler))
            {
                return(handler.Handle(token, remoteObject));
            }
            return(InvalidTypeRepsonse(remoteObject));
        }
コード例 #16
0
        public override void Process(DaemonPacket packet)
        {
            AsyncUserToken socketToken = packet.Session as AsyncUserToken;

            if (socketToken.IsClient)
            {
                Heart.Delayed(packet.TimeNow);
            }
            else
            {
                socketToken.SendAsync(new DaemonPacket()
                {
                    TimeNow = packet.TimeNow
                });
            }
        }
コード例 #17
0
ファイル: SocketManager.cs プロジェクト: lxc1030/ServerTest
 /// <summary>
 /// Socket 断开处理
 /// </summary>
 private void CloseClientSocket(AsyncUserToken userToken)
 {
     try
     {
         if (userToken.ConnectSocket == null)
         {
             return;
         }
         Log4Debug(String.Format("客户 {0} 清理链接!", userToken.ConnectSocket.RemoteEndPoint.ToString()));
         //
         DisConnect();
     }
     catch
     {
     }
 }
コード例 #18
0
        public override void OnUserDisconnect(AsyncUserToken userToken)
        {
            var identity = (ServerSideTokenIdentity)userToken.info;

            ThreadUtils.RepeatingTimeoutLock(
                identity.MatchmakingLock,
                () => ResolveMatchmakingStatusOnQuit(userToken),
                millisecondsTimeOut: 1,
                maxAttempts: 0,
                interAttemptyDelay: 5
                );

            UserConnectionList.GetInstance().LogOutUserUnderIdentity(identity);
            identity.Reset();
            Console.WriteLine("User disconnected");
        }
コード例 #19
0
ファイル: SocketManager.cs プロジェクト: lxc1030/ServerTest
    /// <summary>
    /// 异步发送操作完成后调用该方法
    /// </summary>
    private void ProcessSend(SocketAsyncEventArgs arg)
    {
        MySocketEventArgs e = (MySocketEventArgs)arg;

        //SocketAsyncEventArgs e = userToken.SAEA_Send;
        e.IsUsing = false;
        if (e.SocketError == SocketError.Success)
        {
        }
        else if (e.SocketError == SocketError.Shutdown)
        {
            AsyncUserToken userToken = (AsyncUserToken)e.UserToken;
            CloseClientSocket(userToken);
            Log4Debug("Socket已断线");
        }
    }
コード例 #20
0
        public IRemoteObject Handle(AsyncUserToken token, IRemoteObject request)
        {
            CardListResponse cardListResponse = request as CardListResponse;

            if (cardListResponse.UpToDate)
            {
                Console.WriteLine("Imam najnoviju verziju!");
            }
            else
            {
                CardList cardList = cardListResponse.CardList;
                Console.WriteLine("Stigla nova lista karata, verzija: " + cardList.Vesion);
            }

            return(null);
        }
コード例 #21
0
        private void CloseClientSocket(SocketAsyncEventArgs args)
        {
            AsyncUserToken token = args.UserToken as AsyncUserToken;

            try
            {
                token.Socket.Shutdown(SocketShutdown.Send);
            }
            catch (Exception) { }
            token.Socket.Close();
            token.Socket   = null;
            args.UserToken = new AsyncUserToken();
            _waitLock.Set();

            _logger.LogInformation($"{token.Local} <=> {token.Remote} 断开连接");
        }
コード例 #22
0
ファイル: TCPClient.cs プロジェクト: shuimo1008/Smlib
        protected bool OnSendAsync(SocketAsyncEventArgs iSocketAsyncEventArgs)
        {
            AsyncUserToken oSocketToken = iSocketAsyncEventArgs.UserToken as AsyncUserToken;

            oSocketToken.ActiveDateTime = DateTime.Now;

            if (iSocketAsyncEventArgs.SocketError == SocketError.Success)
            {
                return(oSocketToken.SendAsyncCompleted()); //调用子类回调函数
            }
            else
            {
                CloseSocket(oSocketToken);
                return(false);
            }
        }
コード例 #23
0
        private bool HandleRequest(byte[] data, int offset, int count, SocketAsyncEventArgs e)
        {
            try
            {
                AsyncUserToken token  = e.UserToken as AsyncUserToken;
                Socket         socket = token.WorkSocket;

                //
                logger.Info("Handle request: {0} bytes {1} buffer ", count, token.BufferCount);

                using (StreamReader sr = new StreamReader(new MemoryStream(data, offset, count)))
                {
                    string   line       = sr.ReadLine();
                    string[] firstLines = line.Split(' ');
                    string   method     = firstLines[0];
                    string   path       = firstLines[1];
                    string   host       = "";
                    while ((line = sr.ReadLine()) != null)
                    {
                        int index = line.IndexOf(':');
                        if (index != -1)
                        {
                            if (line.Substring(0, index).Equals("host", StringComparison.OrdinalIgnoreCase))
                            {
                                host = line.Substring(index + 1);
                                break;
                            }
                        }
                    }
                    logger.Info(method + " " + host + path);
                }

                //转发数据
                e.SetBuffer(data, offset, count);
                bool willRaiseEvent = token.WorkSocket.SendAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessSend(e);
                }

                return(true);
            }catch (Exception ex)
            {
                logger.Error("handle exception: " + ex.Message);
                throw;
            }
        }
コード例 #24
0
        /// <summary>
        /// 异步接收操作完成后调用该方法
        /// </summary>
        //private void ProcessReceive(SocketAsyncEventArgs e)
        //{
        //    try
        //    {
        //        if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
        //        {
        //            AsyncUserToken userToken = (AsyncUserToken)e.UserToken;
        //            userToken.HeartbeatTime = DateTime.Now;
        //            string sClientIP = ((IPEndPoint)userToken.S.RemoteEndPoint).Address.ToString();
        //            try
        //            {
        //                byte[] abFactReceive = new byte[e.BytesTransferred];
        //                Array.Copy(e.Buffer, e.Offset, abFactReceive, 0, e.BytesTransferred);

        //                string info = "";
        //                for (int i = 0; i < abFactReceive.Length; i++)
        //                {
        //                    info += abFactReceive[i] + ",";
        //                }
        //                Log4Debug("From the " + sClientIP + " to receive " + e.BytesTransferred + " bytes of data:" + info);

        //                lock (userToken.ReceiveBuffer)
        //                {
        //                    for (int i = 0; i < abFactReceive.Length; i++)
        //                    {
        //                        userToken.ReceiveBuffer.Enqueue(abFactReceive[i]);
        //                    }
        //                }

        //                byte[] data = abFactReceive;
        //                lock (userToken.SendBuffer)
        //                {
        //                    Log4Debug("保存数据:" + data[0]);
        //                    for (int i = 0; i < data.Length; i++)
        //                    {
        //                        userToken.SendBuffer.Enqueue(data[i]);
        //                    }
        //                }
        //                Send(userToken.SAEA_Send);
        //            }
        //            catch (Exception error)
        //            {
        //                Log4Debug(error.Message);
        //            }
        //            finally
        //            {
        //                if (!userToken.S.ReceiveAsync(e))
        //                    ProcessReceive(e);
        //            }
        //        }
        //        else
        //        {
        //            CloseClientSocket(e);
        //        }
        //    }
        //    catch { }
        //}
        #region Receive
        private void ProcessReceive(AsyncUserToken userToken)
        {
            SocketAsyncEventArgs e = userToken.SAEA_Receive;

            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                //if (userToken.userInfo != null)
                //{
                //    userToken.userInfo.heartbeatTime = DateTime.Now;
                //}
                string sClientIP = ((IPEndPoint)userToken.ConnectSocket.RemoteEndPoint).Address.ToString();
                //try
                {
                    byte[] copy = new byte[e.BytesTransferred];
                    Array.Copy(e.Buffer, e.Offset, copy, 0, e.BytesTransferred);
                    string debug = "Receve " + copy.Length + " :";
                    for (int i = 0; i < copy.Length; i++)
                    {
                        debug += copy[i] + ",";
                    }
                    Log4Debug(debug);
                    //
                    //lock (userToken.ReceiveBuffer)
                    //{
                    //    userToken.ReceiveBuffer.AddRange(copy);
                    //}
                    if (!userToken.ConnectSocket.ReceiveAsync(e))
                    {
                        ProcessReceive(userToken);
                    }

                    //if (!userToken.isDealReceive)
                    //{
                    //    userToken.isDealReceive = true;
                    //    Handle(userToken);
                    //}
                }
                //catch (Exception error)
                //{
                //    Log4Debug(error.Message);
                //}
            }
            else
            {
                CloseClientSocket(userToken);
            }
        }
コード例 #25
0
    public IRemoteObject Handle(AsyncUserToken token, IRemoteObject request)
    {
#if UNITY_EDITOR
        try
        {
#endif
        Handle(request as T);
#if UNITY_EDITOR
    }

    catch (Exception e)
    {
        executionQueue.Add(() => Debug.Log("Izuzetak: " + e.Message));
    }
#endif
        return(null);
    }
コード例 #26
0
        public void ExitQueue(AsyncUserToken token)
        {
            ServerSideTokenIdentity identity = (ServerSideTokenIdentity)token.info;

            lock (matchingLock)
            {
                lock (identity.MatchmakingLock)
                {
                    if (userWaitingForMatch == null || userWaitingForMatch.Token != token)
                    {
                        throw new MatchmakingException("Korisnik ne ceka u redu");
                    }
                    identity.MatchmakingStatus = UserMatchmakingStatus.LOBBY;
                    userWaitingForMatch        = null;
                }
            }
        }
コード例 #27
0
        private void RaiseErrorEvent(AsyncUserToken token, AsyncSocketException exception)
        {
            EventHandler <AsyncSocketErrorEventArgs> handler = OnClientError;

            // 如果订户事件将为空(null)
            if (handler != null)
            {
                if (null != token)
                {
                    handler(token, new AsyncSocketErrorEventArgs(exception));//抛出客户端错误事件
                }
                else
                {
                    handler(null, new AsyncSocketErrorEventArgs(exception));//抛出服务器错误事件
                }
            }
        }
コード例 #28
0
 public void Send(SocketAsyncEventArgs e, byte[] bytes, int size)
 {
     AsyncUserToken token = (AsyncUserToken)e.UserToken;
     SocketAsyncEventArgs writeEventArgs = m_writePool.Pop();
     writeEventArgs.UserToken = token;
     byte[] bytesRealSend = new byte[bytes.Length+4];
     byte[] bytesHeader = System.BitConverter.GetBytes(bytes.Length);
     Array.Copy(bytesHeader, 0, bytesRealSend, 0, 4);
     Array.Copy(bytes, 0, bytesRealSend, 4, bytes.Length);
     writeEventArgs.SetBuffer(bytesRealSend, 0, bytesRealSend.Length);
     //writeEventArgs.SetBuffer(bytes, 0, size);
     bool willRaiseEvent = token.Socket.SendAsync(writeEventArgs);
     if (!willRaiseEvent)
     {
         ProcessSend(e);
     }
 }
コード例 #29
0
        private void ProcessSend(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                AsyncUserToken token = (AsyncUserToken)e.UserToken;

                bool willRaiseEvent = token.Socket.ReceiveAsync(e);
                if (!willRaiseEvent)
                {
                    this.ProcessReceive(e);
                }
            }
            else
            {
                this.CloseClientSocket(e);
            }
        }
コード例 #30
0
        private void TcpServer_ClientReceiveData(AsyncUserToken userToken, byte[] data)
        {
            if (!shareDesktop)
            {
                return;
            }
            bool isExist = false;

            lock (rdViewers)
            {
                if (rdViewers.ContainsKey(userToken.Identifier))
                {
                    isExist = true;
                }
            }
            if (!isExist)
            {
                ResMsg rm = Authentication(data);
                if (rm.Result)
                {
                    ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(state =>
                    {
                        AsyncUserToken asyncUserToken = (AsyncUserToken)state;
                        asyncUserToken.SendData(Encoding.ASCII.GetBytes("login ok!"));
                    }), userToken);
                    RDViewer viewer = new RDViewer()
                    {
                        UserName  = rm.Message,
                        UserToken = userToken
                    };
                    lock (rdViewers)
                    {
                        rdViewers.Add(userToken.Identifier, viewer);
                    }
                    ShowLog(viewer.UserName + "开始观看,来源:" + userToken.Identifier);
                }
            }
            else
            {
                lock (recvBuffer)
                {
                    recvBuffer.AddRange(data);
                }
            }
        }
コード例 #31
0
            public EventArgsPoolManager(int capacity)
            {
                mPool = new Stack<SocketAsyncEventArgs>(capacity);
                mSyncroot = new object();
                mCapacity = capacity;
                mSema = new Semaphore(capacity, capacity);

                for (int i = (capacity - 1); i >= 0; i--)
                {
                  AsyncUserToken token = new AsyncUserToken() { TokenId = i };
                  SocketAsyncEventArgs arg = new SocketAsyncEventArgs();
                  arg.UserToken = token;
                  mPool.Push(arg);
                }
            }
コード例 #32
0
ファイル: UdpServerBase.cs プロジェクト: hhahh2011/CH.Gps
        // Initializes the server by preallocating reusable buffers and 
        // context objects.  These objects do not need to be preallocated 
        // or reused, but it is done this way to illustrate how the API can 
        // easily be used to create reusable objects to increase server performance.
        /// <summary>
        /// 初始化服务器相关数据
        /// </summary>
        private void InitData()
        {
            try
            {
                // Allocates one large byte buffer which all I/O operations use a piece of.  This gaurds 
                // against memory fragmentation
                bufferManager.InitBuffer();

                // preallocate pool of SocketAsyncEventArgs objects
                SocketAsyncEventArgs readWriteEventArg;

                for (int i = 0; i < maxConnections; i++)
                {
                    //Pre-allocate a set of reusable SocketAsyncEventArgs
                    readWriteEventArg = new SocketAsyncEventArgs();
                    readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
                    readWriteEventArg.UserToken = new AsyncUserToken();

                    // assign a byte buffer from the buffer pool to the SocketAsyncEventArg object
                    bufferManager.SetBuffer(readWriteEventArg);

                    // add SocketAsyncEventArg to the pool
                    readWritePool.Push(readWriteEventArg);
                }

                //初始化接收消息消息异步对象
                recvArgs = new SocketAsyncEventArgs();
                AsyncUserToken UserTocken = new AsyncUserToken();
                UserTocken.socket = udpListener;
                recvArgs.UserToken = UserTocken;
                byte[] buffer = new byte[bufferSize * opsToPreAlloc];
                recvArgs.SetBuffer(buffer, 0, bufferSize * opsToPreAlloc);
                recvArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                recvArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, null);
            }
       }
コード例 #33
0
        private void ProcessReceivedData(int dataStartOffset, int totalReceivedDataSize, int alreadyProcessedDataSize, AsyncUserToken token, SocketAsyncEventArgs e)
        {
            if (alreadyProcessedDataSize >= totalReceivedDataSize)
            {
                return;
            }

            if (token.MessageSize == null)
            {
                //���֮ǰ���յ������ݼ��ϵ�ǰ���յ������ݴ�����Ϣͷ�Ĵ�С������Խ�����Ϣͷ
                if (totalReceivedDataSize > MessageHeaderSize)
                {
                    //������Ϣ����
                    var headerData = new byte[MessageHeaderSize];
                    Buffer.BlockCopy(e.Buffer, dataStartOffset, headerData, 0, MessageHeaderSize);
                    var messageSize = BitConverter.ToInt32(headerData, 0);

                    token.MessageSize = messageSize;
                    token.DataStartOffset = dataStartOffset + MessageHeaderSize;

                    //�ݹ鴦��
                    ProcessReceivedData(token.DataStartOffset, totalReceivedDataSize, alreadyProcessedDataSize + MessageHeaderSize, token, e);
                }
                //���֮ǰ���յ������ݼ��ϵ�ǰ���յ���������Ȼû�д�����Ϣͷ�Ĵ�С������Ҫ�������պ������ֽ�
                else
                {
                    //���ﲻ��Ҫ��ʲô����
                }
            }
            else
            {
                var messageSize = token.MessageSize.Value;
                //�жϵ�ǰ�ۼƽ��յ����ֽ�����ȥ�Ѿ�������ֽ����Ƿ������Ϣ�ij��ȣ�������ڣ���˵�����Խ�����Ϣ��
                if (totalReceivedDataSize - alreadyProcessedDataSize >= messageSize)
                {
                    var messageData = new byte[messageSize];
                    Buffer.BlockCopy(e.Buffer, dataStartOffset, messageData, 0, messageSize);
                    ProcessMessage(messageData, token, e);

                    //��Ϣ���������Ҫ����token���Ա������һ����Ϣ
                    token.DataStartOffset = dataStartOffset + messageSize;
                    token.MessageSize = null;

                    //�ݹ鴦��
                    ProcessReceivedData(token.DataStartOffset, totalReceivedDataSize, alreadyProcessedDataSize + messageSize, token, e);
                }
                //˵��ʣ�µ��ֽ���������ת��Ϊ��Ϣ������Ҫ�������պ������ֽ�
                else
                {
                    //���ﲻ��Ҫ��ʲô����
                }
            }
        }
コード例 #34
0
 private void ProcessMessage(byte[] messageData, AsyncUserToken token, SocketAsyncEventArgs e)
 {
     var current = Interlocked.Increment(ref _receivedMessageCount);
     if (current == 1)
     {
         _watch = Stopwatch.StartNew();
     }
     if (current % 10000 == 0)
     {
         Console.WriteLine("received message, length:{0}, count:{1}, timeSpent:{2}", messageData.Length, current, _watch.ElapsedMilliseconds);
     }
     sendingQueue.Add(new MessageData { Message = messageData, Token = token });
 }