Пример #1
0
        internal void ProcessSend(SocketAsyncEventArgs Args)
        {
            T Session = (T)Args.UserToken;

            if (Args.SocketError == SocketError.Success)
            {
                Session.SendBytesRemainingCount = Session.SendBytesRemainingCount - Args.BytesTransferred;

                if (Session.SendBytesRemainingCount == 0)
                {
                    SendPool.Push(Args);
                }
                else
                {
                    Session.BytesSentAlreadyCount += Args.BytesTransferred;
                    StartSend(Args);
                }

                if (DataSent != null)
                {
                    DataSent.Invoke(new SocketSentEventArgs <T>(Session, Session.DataToSend, Args.BytesTransferred));
                }
            }
            else
            {
                CloseClientSocket(Args);
                SendPool.Push(Args);
            }
        }
Пример #2
0
        private void WritePort(string text, bool addOk = true)
        {
            _comm.WritePort(text);
            if (DataSent != null)
            {
                DataSent.Invoke(this, text);
            }

            if (addOk && text != "ok")
            {
                _comm.WritePort("ok");
                if (DataSent != null)
                {
                    DataSent.Invoke(this, "ok");
                }
            }
        }
Пример #3
0
        private void WritePort(string[] text, bool addOk = true)
        {
            foreach (string c in text)
            {
                _comm.WritePort(c);
                if (DataSent != null)
                {
                    DataSent.Invoke(this, c);
                }
            }

            if (addOk)
            {
                _comm.WritePort("ok");
                if (DataSent != null)
                {
                    DataSent.Invoke(this, "ok");
                }
            }
        }
Пример #4
0
        public void SendGameAction(GameAction gameAction, GameAction.IParameters parameters)
        {
            if (State == ClientState.Debug)
            {
                return;
            }
            if (State != ClientState.Connected)
            {
                throw new InvalidOperationException($"Cannot send game action {gameAction}: not connected");
            }

            DataStreamWriter streamWriter = _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection);

            streamWriter.WriteInt(Commands.GameAction);
            streamWriter.WriteInt(GameActionManager.Instance.GetID(gameAction));
            streamWriter.WriteInt(ActorNumber);
            streamWriter.WriteFloat(Server.Time);
            gameAction.SerializeParameters(ref streamWriter, parameters);
            _clientDriver.EndSend(streamWriter);
            DataSent?.Invoke(streamWriter.Length);
        }
Пример #5
0
        public void SendRPC(NetBehaviour netBehaviour, string methodName, object[] args)
        {
            if (State == ClientState.Debug)
            {
                return;
            }
            if (State != ClientState.Connected)
            {
                throw new InvalidOperationException($"Cannot send rpc {methodName}: not connected");
            }

            DataStreamWriter streamWriter = _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection);

            streamWriter.WriteInt(Commands.NetObjectRPC);
            streamWriter.WriteFloat(Server.Time);
            streamWriter.WriteInt(netBehaviour.NetObject.ID);
            streamWriter.WriteUShort(netBehaviour.NetBehaviourID);
            NetObjectManager.Instance.SerializeRPC(ref streamWriter, netBehaviour, methodName, args);
            _clientDriver.EndSend(streamWriter);
            DataSent?.Invoke(streamWriter.Length);
        }
Пример #6
0
        public TLCFIClientSession(TLCFIClientStateManager stateManager, IPEndPoint ep, CancellationToken token)
        {
            _endPoint = ep;
            _sessionCancellationToken = token;
            _stateManager             = stateManager;

            Client               = new TwoWayTcpClient();
            Client.DataSent     += (o, e) => { DataSent?.Invoke(this, e); };
            Client.Disconnected += Client_Disconnected;

            RemoteEndPoint = ep;

            State = new TLCFIClientSessionState();

            TLCProxy        = new TLCProxy(Client);
            _jsonRpcHandler = new TLCFIClientSessionJsonRpcHandler(stateManager, TLCProxy, State, Client, token);
            _jsonRpcHandler.ReceivedAlive += (o, a) =>
            {
                _aliveReceivedTimer.Stop();
                _aliveReceivedTimer.Start();
            };
            _jsonRpcHandler.UpdateStateCalled += OnUpdateStateCalled;
            _jsonRpcHandler.NotifyEventCalled += OnNotifyEventCalled;
        }
Пример #7
0
        public void SendBatchedNetObjectsUpdate()
        {
            if (State == ClientState.Debug)
            {
                return;
            }
            if (State != ClientState.Connected)
            {
                Debug.LogWarning($"Cannot send messages in client state {State}");
                return;
            }

            if (IsHost)
            {
                return;
            }

            NetObject[] netObjects = NetObjectManager.Instance.NetObjects;

            const int headerSizeInBytes = 8;
            var       streamWriter      = new DataStreamWriter(MaxBytesPerMessage, Allocator.Temp);
            var       objectWriter      = new DataStreamWriter(MaxBytesPerMessage - headerSizeInBytes, Allocator.Temp);
            var       objectIndex       = 0;

            // compose new message if objects left to send or serialize
            while (objectIndex < netObjects.Length || objectWriter.Length > 0)
            {
                // header
                streamWriter.Clear();
                streamWriter.WriteInt(Commands.UpdateNetObjects);
                DataStreamWriter objectCountWriter = streamWriter;
                streamWriter.WriteInt(0);

                // add items as long as they fit
                var objectsInMessage = 0;
                while (streamWriter.Length + objectWriter.Length <= MaxBytesPerMessage)
                {
                    if (objectWriter.Length > 0)
                    {
                        streamWriter.WriteBytes(objectWriter.AsNativeArray());
                        objectWriter.Clear();
                        objectsInMessage++;
                    }

                    // next object. Write if dirty and controlled by this client
                    if (objectIndex < netObjects.Length)
                    {
                        NetObject netObject = netObjects[objectIndex++];
                        if (netObject.IsDirty && netObject.IsMine)
                        {
                            WriteNetObject(netObject, ref objectWriter);
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                objectCountWriter.WriteInt(objectsInMessage);

                // message complete. Send if payload exists
                if (objectsInMessage > 0)
                {
                    DataStreamWriter writer = _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection);
                    writer.WriteBytes(streamWriter.AsNativeArray());
                    _clientDriver.EndSend(writer);
                    DataSent?.Invoke(writer.Length);
                }
            }
        }
Пример #8
0
        public void Tick()
        {
            if (!_clientDriver.IsCreated)
            {
                return;
            }
            _clientDriver.ScheduleUpdate().Complete();

            if (_timeout > 0 && IsConnected && Time.time - LastPongTime > _timeout)
            {
                Debug.LogWarning("Disconnected due to timeout");
                Disconnect();
                return;
            }

            // listen for events
            NetworkEvent.Type eventType;
            while ((eventType = _clientToServerConnection.PopEvent(_clientDriver, out DataStreamReader streamReader))
                   != NetworkEvent.Type.Empty)
            {
                if (eventType == NetworkEvent.Type.Connect)
                {
                    Debug.Log("Connected!");
                    State = ClientState.Connected;
                    Connected?.Invoke();
                }
                else if (eventType == NetworkEvent.Type.Data)
                {
                    DataReceived?.Invoke(streamReader.Length);
                    int command = streamReader.ReadInt();
                    switch (command)
                    {
                    case Commands.AssignActorNumber:
                    {
                        ActorNumber = streamReader.ReadInt();
                        Debug.Log($"Got assigned actor number {ActorNumber}");
                        DataStreamWriter writer =
                            _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection);
                        writer.WriteInt(Commands.AcknowledgeActorNumber);
                        _clientDriver.EndSend(writer);
                        DataSent?.Invoke(writer.Length);
                        break;
                    }

                    case Commands.AcceptPlayer:
                    {
                        DataStreamWriter writer =
                            _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection);
                        writer.WriteInt(Commands.RequestSpawnMessage);
                        writer.WriteInt(SceneManager.sceneCount);
                        for (var i = 0; i < SceneManager.sceneCount; i++)
                        {
                            writer.WriteInt(SceneManager.GetSceneAt(i).buildIndex);
                        }
                        SceneManager.sceneLoaded += OnSceneLoaded;
                        _clientDriver.EndSend(writer);
                        break;
                    }

                    case Commands.Ping:
                    {
                        LastPongTime = Time.time;
                        float sendLocalTime   = streamReader.ReadFloat();
                        float serverTime      = streamReader.ReadFloat();
                        float serverDeltaTime = streamReader.ReadFloat();
                        RoundTripTime = Time.time - sendLocalTime;
                        Latency       = IsHost
                                ? 0
                                : Mathf.Max(0, (RoundTripTime - serverDeltaTime / 2 - Time.deltaTime / 2) / 2);
                        // estimated server time NOW is received serverTime + latency for one trip + average frame wait on client side
                        float serverTimeOffset = serverTime - Time.time + Latency + Time.deltaTime / 2;
                        _averageServerTimeOffset = Mathf.Abs(_averageServerTimeOffset - serverTime) > 0.5f
                                ? serverTimeOffset
                                : 0.9f * _averageServerTimeOffset + 0.1f * serverTimeOffset;
                        PingReceived?.Invoke(RoundTripTime, Latency);
                        break;
                    }

                    case Commands.SpawnNetObjects:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int count = streamReader.ReadInt();

                        for (var i = 0; i < count; i++)
                        {
                            int        netObjID         = streamReader.ReadInt();
                            ushort     prefabIndex      = streamReader.ReadUShort();
                            int        ownerActorNumber = streamReader.ReadInt();
                            Vector3    position         = streamReader.ReadVector3();
                            Quaternion rotation         = streamReader.ReadQuaternion();
                            int        sceneBuildIndex  = streamReader.ReadInt();
                            int        size             = streamReader.ReadInt();
                            int        bytesRead        = streamReader.GetBytesRead();
                            Scene      scene            = SceneManager.GetSceneByBuildIndex(sceneBuildIndex);
                            var        deserialized     = false;
                            if (scene != null && scene.isLoaded)
                            {
                                NetObject netObject = NetObjectManager.Instance.SpawnOnClient(netObjID, prefabIndex,
                                                                                              ownerActorNumber, position, rotation, scene);
                                if (netObject != null)
                                {
                                    netObject.Deserialize(ref streamReader, behaviour => true);
                                    deserialized = true;
                                }
                            }

                            if (!deserialized)
                            {
                                streamReader.DiscardBytes(size);
                            }
                            if (streamReader.GetBytesRead() - bytesRead != size)
                            {
                                Debug.LogWarning("Did not deserialize properly!");
                            }
                        }

                        break;
                    }

                    case Commands.UpdateNetAssets:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int assetsInMessage = streamReader.ReadInt();
                        for (var i = 0; i < assetsInMessage; i++)
                        {
                            int assetNetID = streamReader.ReadInt();
                            int size       = streamReader.ReadInt();
                            int bytesRead  = streamReader.GetBytesRead();
                            try
                            {
                                NetAsset netAsset = NetAssetManager.Instance.Get(assetNetID);
                                netAsset.Deserialize(ref streamReader);
                            }
                            catch (Exception e)
                            {
                                Debug.LogException(new NetException($"Failed to update net asset {assetNetID}", e));
                                streamReader.DiscardBytes(size + bytesRead - streamReader.GetBytesRead());
                            }
                        }

                        break;
                    }

                    case Commands.UpdateNetObjects:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int objectsInMessage = streamReader.ReadInt();
                        for (var i = 0; i < objectsInMessage; i++)
                        {
                            int netObjID = streamReader.ReadInt();
                            int size     = streamReader.ReadInt();
                            if (NetObjectManager.Instance.Exists(netObjID))
                            {
                                NetObject netObject = NetObjectManager.Instance.Get(netObjID);
                                int       bytesRead = streamReader.GetBytesRead();
                                try
                                {
                                    netObject.Deserialize(ref streamReader, behaviour => !behaviour.HasAuthority);
                                }
                                catch (Exception e)
                                {
                                    Debug.LogException(
                                        new NetException($"Failed to update net object {netObjID}", e));
                                    streamReader.DiscardBytes(size + bytesRead - streamReader.GetBytesRead());
                                }
                            }
                            else
                            {
                                streamReader.DiscardBytes(size);
                            }
                        }

                        break;
                    }

                    case Commands.UnspawnNetObjects:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int count = streamReader.ReadInt();
                        for (var i = 0; i < count; i++)
                        {
                            int netObjID = streamReader.ReadInt();
                            NetObjectManager.Instance.Unspawn(netObjID);
                        }

                        break;
                    }

                    case Commands.GameAction:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int   gameActionID = streamReader.ReadInt();
                        int   actorNumber  = streamReader.ReadInt();
                        float triggerTime  = streamReader.ReadFloat();
                        bool  valid        = streamReader.ReadBool();
                        try
                        {
                            GameAction             gameAction = GameActionManager.Instance.Get(gameActionID);
                            GameAction.IParameters parameters = gameAction.DeserializeParameters(ref streamReader);
                            gameAction.ReceiveOnClient(parameters, valid, actorNumber, triggerTime);
                            break;
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                            break;
                        }
                    }

                    case Commands.NetAssetRPC:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        float        sentServerTime = streamReader.ReadFloat();
                        int          netAssetID     = streamReader.ReadInt();
                        NetAsset     netAsset       = NetAssetManager.Instance.Get(netAssetID);
                        NetAsset.RPC rpc            = netAsset.DeserializeRPC(ref streamReader);
                        var          messageInfo    = new MessageInfo
                        {
                            SentServerTime = sentServerTime, SenderActorNumber = Server.ServerActorNumber
                        };
                        rpc.Invoke(messageInfo);
                        break;
                    }

                    case Commands.NetObjectRPC:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        float sentServerTime = streamReader.ReadFloat();
                        int   netObjectID    = streamReader.ReadInt();
                        if (!NetObjectManager.Instance.Exists(netObjectID))
                        {
                            Debug.LogWarning("Ignoring received RPC, because NetObject was not found.");
                            break;
                        }

                        NetObject            netObject      = NetObjectManager.Instance.Get(netObjectID);
                        ushort               netBehaviourID = streamReader.ReadUShort();
                        NetBehaviour         netBehaviour   = netObject.Get(netBehaviourID);
                        NetObjectManager.RPC rpc            =
                            NetObjectManager.Instance.DeserializeRPC(ref streamReader, netBehaviour);
                        var messageInfo = new MessageInfo
                        {
                            SentServerTime = sentServerTime, SenderActorNumber = Server.ServerActorNumber
                        };
                        rpc.Invoke(messageInfo);
                        break;
                    }

                    default:
                        Debug.LogError($"Unknown event type {eventType}");
                        break;
                    }
                }
                else if (eventType == NetworkEvent.Type.Disconnect)
                {
                    Debug.Log("Disconnected!");
                    SceneManager.sceneLoaded -= OnSceneLoaded;
                    Disconnected?.Invoke();
                    State = ClientState.Disconnected;
                    _clientToServerConnection = default;
                }
            }
        }
Пример #9
0
 protected virtual void OnDataSent(object sender, Socket_EventArgs e)
 {
     DataSent?.Invoke(sender, e);
 }
Пример #10
0
 private void OnDataSent(string dataSent)
 {
     DataSent?.Invoke(dataSent);
 }
Пример #11
0
 protected virtual void OnDataSent(DataSentEventArgs e)
 {
     DataSent?.Invoke(this, e);
 }
Пример #12
0
 internal void OnDataSent(byte[] buffer, int offset, int count)
 {
     DataSent?.Invoke(this, new DataEventArgs(buffer, offset, count));
 }
Пример #13
0
 internal virtual void OnDataSent(DataSentEventArgs e) => DataSent?.Invoke(this, e);
Пример #14
0
 /// <summary>Метод вызова события "при передаче данных"</summary>
 protected virtual void InvokeDataSendEvent(ClientDataEventArgs e) => DataSent?.Invoke(this, e);
Пример #15
0
 public Task SendAsync(byte[] data, CancellationToken cancellationToken)
 {
     DataSent?.Invoke(this, data);
     return(Task.CompletedTask);
 }
Пример #16
0
 public void Send(byte[] data)
 {
     DataSent?.Invoke(this, data);
 }
Пример #17
0
 private void HandleDataSent(object sender, ConnectionArgs e)
 {
     DataSent?.Invoke(sender, e);
 }
Пример #18
0
 public void SendMessage(object recipientKey, DataBuffer data)
 {
     (recipientKey as DirectClientProvider).ReceiveMessage(data);
     DataSent?.Invoke(this, new ProviderDataEventArgs(recipientKey, false, null, data.GetLength()));
 }
Пример #19
0
        public void Send(string cmd)
        {
            DataSent?.Invoke(this, ">>" + cmd);

            //if (ConnectionState != ConnectionStatus.Connected) { return; }

            try
            {
                DoSend(_TCP.Client, cmd);
            }
            catch (IOException ex)
            {
                //System.IO.IOException
                //Unable to transfer data on the transport connection: An established connection was aborted by the software in your host machine.

                //System.Diagnostics.Debug.WriteLine("**Error@Send: IOException - TRYING TO RECONNECT.");
                System.Diagnostics.Debug.WriteLine("**Error@Send: IOException:" + ex.Message);

                ConnectionState = ConnectionStatus.DisconnectedByHost;
                ConnectionError?.Invoke(this, ex.Message);

                /*
                 * // Reconnect.
                 * if (await ReConnect())
                 * {
                 *  DoSend(_TCP.Client, cmd);
                 * }
                 * else
                 * {
                 *  System.Diagnostics.Debug.WriteLine("**Error@Send: IOException - GIVING UP reconnect.");
                 *
                 * }
                 */
            }
            catch (SocketException ex)
            {
                //System.Net.Sockets.SocketException
                //An established connection was aborted by the software in your host machine
                //System.Diagnostics.Debug.WriteLine("**Error@Send: SocketException - TRYING TO RECONNECT.");

                System.Diagnostics.Debug.WriteLine("**Error@Send: SocketException:" + ex.Message);

                ConnectionState = ConnectionStatus.Error;
                ConnectionError?.Invoke(this, ex.Message);

                /*
                 * // Reconnect.
                 * if (await ReConnect())
                 * {
                 *  DoSend(_TCP.Client, cmd);
                 * }
                 * else
                 * {
                 *  System.Diagnostics.Debug.WriteLine("**Error@Send: SocketException - GIVING UP reconnect.");
                 *  ConnectionState = ConnectionStatus.DisconnectedByHost;
                 * }
                 */
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("**Error@Send: " + ex.Message);
                ConnectionState = ConnectionStatus.Error;
                ConnectionError?.Invoke(this, ex.Message);
            }
        }
Пример #20
0
 protected void OnDataSent() => DataSent?.Invoke(this, e);
Пример #21
0
 public void SendMessage(DataBuffer data)
 {
     ActiveServer.ReceiveMessage(this, data);
     DataSent?.Invoke(this, new ProviderDataEventArgs(null, false, null, data.GetLength()));
 }
Пример #22
0
 /// <summary>
 /// Raises the DataSent event
 /// </summary>
 /// <param name="messageEventArgs"></param>
 protected override void OnDataSent(SockMessageEventArgs e)
 {
     DataSent?.Invoke(this, e);
 }
Пример #23
0
 protected override void RawSend(byte[] data, int length)
 {
     DataSent?.Invoke(length);
     socket.SendTo(data, 0, length, SocketFlags.None, remoteEndpoint);
 }
Пример #24
0
 /// <summary>The event handler for the 'data sent' event.</summary>
 /// <param name="sender">The connection that originated this event.</param>
 /// <param name="args">The connection arguments for this event.</param>
 private void EventHandlerDataSent(object sender, ConnectionArgs args)
 {
     DataSent?.Invoke(sender, args);
 }
Пример #25
0
 protected void OnDataSent(DialogDataEventArgs e)
 {
     DataSent?.Invoke(this, e);
 }
Пример #26
0
 internal void HandleDataSent(object sender, DataSentEventArgs args)
 {
     DataSent?.Invoke(sender, args);
 }
Пример #27
0
 private void OnDataSent(object sender, EventArgs e)
 {
     DataSent?.Invoke(sender, e);
 }
Пример #28
0
 protected virtual void OnDataSent(ClientNode node, string message)
 {
     DataSent?.Invoke(node, message);
 }
Пример #29
0
 private void OnDataSent(DataEventArgs e)
 {
     DataSent?.Invoke(this, e);
 }