Ejemplo n.º 1
0
 public void ClientOnPackageReceived(IPacketInfo packet)
 {
     try
     {
         var offsets = PacketInfo.GetOffsetInfo(packet.Buffer, packet.Offset);
         foreach (var item in offsets)
         {
             try
             {
                 var operationCode = MessageBase.GetOperationCode(packet.Buffer, item.Offset);
                 if (operationCode != ShamanOperationCode.Bundle)
                 {
                     _logger.Debug($"Shaman message received. Operation code: {operationCode}");
                     _shamanMessageHandler.ProcessMessage(operationCode, packet.Buffer, item.Offset, item.Length);
                 }
                 else
                 {
                     _logger.Debug($"Bundle message received. Operation code: {operationCode}");
                     var bundleOperationCode = MessageBase.GetOperationCode(packet.Buffer, item.Offset + 1);
                     _bundleMessageHandler.ProcessMessage(bundleOperationCode, packet.Buffer, item.Offset + 1, item.Length - 1);
                 }
             }
             catch (Exception ex)
             {
                 _logger.Error(ex);
                 SetAndReportStatus(_status, _statusCallback, false, ex.Message);
             }
         }
     }
     finally
     {
         packet.Dispose();
     }
 }
Ejemplo n.º 2
0
        private void ProcessMessage(byte[] buffer, int offset, int length)
        {
            var operationCode = MessageBase.GetOperationCode(buffer, offset);

            _logger.LogInfo($"Message received. Operation code: {operationCode}");
            if (operationCode != ShamanOperationCode.Bundle)
            {
                _receivedMessages.Add(new RawMessage
                {
                    Data          = buffer.ToArray(),
                    Offset        = offset,
                    Length        = length,
                    OperationCode = operationCode
                });
            }
            else
            {
                var bundleOperationCode = MessageBase.GetOperationCode(buffer, offset + 1);
                _logger.LogInfo($"It is bundle message ! {bundleOperationCode}");
                _receivedMessages.Add(new RawMessage
                {
                    Data          = buffer.ToArray(),
                    Offset        = offset + 1,
                    Length        = length - 1,
                    OperationCode = bundleOperationCode
                });
            }


            //save join info
            if (operationCode == ShamanOperationCode.JoinInfo)
            {
                _joinInfo = _serializer.DeserializeAs <JoinInfoEvent>(buffer, offset, length).JoinInfo;
            }
        }
Ejemplo n.º 3
0
        private void ProcessMessage(byte[] buffer, int offset, int length)
        {
            MessageBase deserialized  = null;
            ushort      operationCode = 0;

            try
            {
                //probably bad kind of using
                var message = new ArraySegment <byte>(buffer, offset, length).ToArray();

                operationCode = MessageBase.GetOperationCode(message);

                _logger.Debug($"Message received. Operation code: {operationCode}");

                deserialized = _messageDeserializer.DeserializeMessage(operationCode, _serializer, message);
            }
            catch (Exception ex)
            {
                _logger.Error($"ClientOnPackageReceived error: {ex}");
            }

            //calling registered handlers
            lock (_syncCollections)
            {
                if (deserialized != null && operationCode != 0 && _handlers.ContainsKey(operationCode))
                {
                    var callbacksToUnregister = new List <Guid>();
                    foreach (var item in _handlers[operationCode])
                    {
                        try
                        {
                            item.Value.Handler.Invoke(deserialized);
                            if (item.Value.CallOnce)
                            {
                                callbacksToUnregister.Add(item.Key);
                            }
                        }
                        catch (Exception ex)
                        {
                            string targetName = item.Value == null ? "" : item.Value.Handler.Method.ToString();
                            _logger.Error($"ClientOnPackageReceived error: processing message {deserialized.OperationCode} in handler {targetName} {ex}");
                        }
                    }

                    //unregister
                    foreach (var item in callbacksToUnregister)
                    {
                        UnregisterOperationHandler(item);
                    }
                }
                else
                {
                    _logger.Debug($"No handler for message {operationCode}");
                }
            }
        }
        public void ProcessMessage(Payload message, DeliveryOptions deliveryOptions, Guid sessionId)
        {
            // var testRoomEvent =
            //     _serializer.DeserializeAs<TestRoomEvent>(message.Buffer, message.Offset, message.Length);
            var operationCode = (byte)MessageBase.GetOperationCode(message.Buffer, message.Offset);

            if (operationCode == TestEventCodes.TestEventCode)
            {
                var deserializedMessage =
                    _serializer.DeserializeAs <TestRoomEvent>(message.Buffer, message.Offset, message.Length);
                _sendManager.SendToAll(deserializedMessage, sessionId);
            }
        }
Ejemplo n.º 5
0
        private void ProcessMessage(IPEndPoint endPoint, Payload payload,
                                    DeliveryOptions deliveryOptions,
                                    GamePeer peer)
        {
            var operationCode = MessageBase.GetOperationCode(payload.Buffer, payload.Offset);

            _logger.Debug($"Message received. Operation code: {operationCode}");

            if (peer == null)
            {
                _logger.Warning($"GamePeerListener.OnReceivePacketFromClient error: can not find peer for endpoint {endPoint.Address}:{endPoint.Port}");
                return;
            }

            //listener handles only auth message, others are sent to roomManager
            switch (operationCode)
            {
            case ShamanOperationCode.Connect:
                _logger.Error($"Sending ConnectedEvent to peer {peer.GetPeerId()}");
                _messageSender.Send(new ConnectedEvent(), peer);
                break;

            case ShamanOperationCode.Ping:
                _messageSender.Send(new PingEvent(), peer);
                break;

            case ShamanOperationCode.Disconnect:
                OnClientDisconnect(endPoint, new SimpleDisconnectInfo(ShamanDisconnectReason.PeerLeave));
                break;

            case ShamanOperationCode.Authorization:
                var authMessage = Serializer.DeserializeAs <AuthorizationRequest>(payload.Buffer, payload.Offset, payload.Length);

                if (!Config.IsAuthOn)
                {
                    //if success - send auth success
                    peer.IsAuthorizing = false;
                    peer.IsAuthorized  = true;
                    //this sessionID will be got from backend, after we send authToken, which will come in player properties
                    peer.SetSessionId(authMessage.SessionId);
                    _messageSender.Send(new AuthorizationResponse(), peer);
                }
                else
                {
                    //TODO authorizing logic
                    throw new NotImplementedException();
                }
                break;

            default:
                if (!peer.IsAuthorized && Config.IsAuthOn)
                {
                    _messageSender.Send(new AuthorizationResponse()
                    {
                        ResultCode = ResultCode.NotAuthorized
                    }, peer);
                    return;
                }
                else
                {
                    if (!peer.IsAuthorized)
                    {
                        _messageSender.Send(new AuthorizationResponse(), peer);
                    }
                }

                switch (operationCode)
                {
                default:
                    _roomManager.ProcessMessage(operationCode, payload, deliveryOptions, peer);
                    break;
                }

                break;
            }
        }
Ejemplo n.º 6
0
        private void ProcessMessage(IPEndPoint endPoint, byte[] buffer, int offset, int length, MmPeer peer)
        {
            //probably bad kind of using
            var operationCode = MessageBase.GetOperationCode(buffer, offset);

            _logger.Debug($"Message received. Operation code: {operationCode}");

            peer = PeerCollection.Get(endPoint);
            if (peer == null)
            {
                _logger.Warning($"GamePeerListener.OnReceivePacketFromClient error: can not find peer for endpoint {endPoint.Address}:{endPoint.Port}");
                return;
            }


            //listener handles only auth message, others are sent to roomManager
            switch (operationCode)
            {
            case ShamanOperationCode.Connect:
                _messageSender.Send(new ConnectedEvent(), peer);
                break;

            case ShamanOperationCode.Ping:
                //ping processing
                break;

            case ShamanOperationCode.Disconnect:
                OnClientDisconnect(endPoint, new SimpleDisconnectInfo(ShamanDisconnectReason.PeerLeave));
                break;

            case ShamanOperationCode.Authorization:
                var authMessage =
                    Serializer.DeserializeAs <AuthorizationRequest>(buffer, offset, length);

                if (!Config.IsAuthOn)
                {
                    //if success - send auth success
                    peer.IsAuthorizing = false;
                    peer.IsAuthorized  = true;
                    //this sessionID will be got from backend, after we send authToken, which will come in player properties
                    peer.SetSessionId(authMessage.SessionId);
                    _messageSender.Send(new AuthorizationResponse(), peer);
                }
                else
                {
                    //TODO authorizing logic
                    throw new NotImplementedException();
                }
                break;

            default:
                if (!peer.IsAuthorized && Config.IsAuthOn)
                {
                    _messageSender.Send(new AuthorizationResponse()
                    {
                        ResultCode = ResultCode.NotAuthorized
                    }, peer);
                    return;
                }
                else
                {
                    if (!peer.IsAuthorized)
                    {
                        _messageSender.Send(new AuthorizationResponse(), peer);
                    }
                }

                switch (operationCode)
                {
                case ShamanOperationCode.PingRequest:
                    _messageSender.Send(new PingResponse(), peer);
                    break;

                case ShamanOperationCode.CreateRoomFromClient:
                    var createRequest =
                        Serializer.DeserializeAs <CreateRoomFromClientRequest>(buffer, offset, length);
                    TaskScheduler.ScheduleOnceOnNow(async() =>
                    {
                        var createResult = await _matchMakingGroupsManager.CreateRoom(peer.GetSessionId(),
                                                                                      createRequest.MatchMakingProperties);
                        //parse create result and create response
                        var createResponse = new CreateRoomFromClientResponse(GetJoinInfo(createResult));
                        if (createResult.Result == RoomOperationResult.OK)
                        {
                            _logger.Info($"Room {createResult.RoomId} created");
                        }
                        _messageSender.Send(createResponse, peer);
                    });
                    break;

                case ShamanOperationCode.DirectJoin:
                    var joinRequest = Serializer.DeserializeAs <DirectJoinRequest>(buffer, offset, length);
                    TaskScheduler.ScheduleOnceOnNow(async() =>
                    {
                        //join existing room
                        var joinResult = await _roomManager.JoinRoom(joinRequest.RoomId,
                                                                     new Dictionary <Guid, Dictionary <byte, object> >
                        {
                            { peer.GetSessionId(), joinRequest.MatchMakingProperties }
                        }, joinRequest.MatchMakingWeight, joinRequest.MatchMakingWeight);
                        //parse join result and create response
                        var joinResponse = new DirectJoinResponse(GetJoinInfo(joinResult));
                        if (joinResult.Result == RoomOperationResult.OK)
                        {
                            _logger.Info($"Player direct joined room {joinResult.RoomId}");
                        }
                        _messageSender.Send(joinResponse, peer);
                    });
                    break;

                case ShamanOperationCode.GetRoomList:
                    var request = Serializer.DeserializeAs <GetRoomListRequest>(buffer, offset, length);
                    var rooms   = _matchMakingGroupsManager.GetRooms(request.MatchMakingProperties)
                                  .Select(r => new RoomInfo(r.Id, r.TotalWeightNeeded, r.CurrentWeight, r.Properties, r.State))
                                  .ToList();
                    var getRoomsResponse = new GetRoomListResponse();
                    getRoomsResponse.Rooms = rooms;
                    _messageSender.Send(getRoomsResponse, peer);
                    break;

                case ShamanOperationCode.EnterMatchMaking:
                    var enterMessage = Serializer.DeserializeAs <EnterMatchMakingRequest>(buffer, offset, length);
                    if (enterMessage == null)
                    {
                        throw new Exception("Can not deserialize EnterMatchMakingRequest. Result is null");
                    }


                    var properties = enterMessage.MatchMakingProperties;

                    var requiredProperties = _matchMaker.GetRequiredProperties();

                    foreach (var property in requiredProperties)
                    {
                        if (!properties.ContainsKey(property))
                        {
                            _logger.Error($"Player {peer.GetPeerId()} tried to enter matchmaking without property {property}");
                            _messageSender.Send(new EnterMatchMakingResponse(MatchMakingErrorCode.RequiredPlayerPropertyIsNotSet), peer);
                            return;
                        }
                    }

                    //add player
                    _matchMaker.AddPlayer(peer, enterMessage.MatchMakingProperties, enterMessage.MatchMakingWeight);

                    _messageSender.Send(new EnterMatchMakingResponse(), peer);

                    break;

                case ShamanOperationCode.LeaveMatchMaking:
                    //remove player
                    _matchMaker.RemovePlayer(peer.GetPeerId());
                    //send response
                    _messageSender.Send(new LeaveMatchMakingResponse(), peer);
                    break;

                default:
                    _messageSender.Send(new ErrorResponse(ResultCode.UnknownOperation), peer);
                    return;
                }

                break;
            }
        }
Ejemplo n.º 7
0
        public void ProcessMessage(Payload message, DeliveryOptions deliveryOptions, Guid sessionId)
        {
            var operationCode = MessageBase.GetOperationCode(message.Buffer, message.Offset);

            Trace($"Message {operationCode} received");
        }