Esempio n. 1
0
        void ProcessClientMessages()
        {
            // note: process even if not connected because when calling
            // Disconnect, we add a Disconnected event which still needs to be
            // processed here.
            while (clientIncoming.Count > 0)
            {
                Message message = clientIncoming.Dequeue();
                switch (message.eventType)
                {
                case EventType.Connected:
                    Debug.Log("MemoryTransport Client Message: Connected");
                    OnClientConnected.Invoke();
                    break;

                case EventType.Data:
                    Debug.Log("MemoryTransport Client Message: Data: " + BitConverter.ToString(message.data));
                    OnClientDataReceived.Invoke(new ArraySegment <byte>(message.data), 0);
                    break;

                case EventType.Disconnected:
                    Debug.Log("MemoryTransport Client Message: Disconnected");
                    OnClientDisconnected.Invoke();
                    break;
                }
            }
        }
Esempio n. 2
0
        public override void ClientConnect(string address)
        {
            if (clientConnection != null)
            {
                Debug.LogWarning("KCP: client already connected!");
                return;
            }

            clientConnection = new KcpClientConnection();
            // setup events
            clientConnection.OnConnected += () =>
            {
                Debug.LogWarning($"KCP->Mirror OnClientConnected");
                OnClientConnected.Invoke();
            };
            clientConnection.OnData += (message) =>
            {
                //Debug.LogWarning($"KCP->Mirror OnClientData({BitConverter.ToString(message.Array, message.Offset, message.Count)})");
                OnClientDataReceived.Invoke(message);
            };
            clientConnection.OnDisconnected += () =>
            {
                Debug.LogWarning($"KCP->Mirror OnClientDisconnected");
                OnClientDisconnected.Invoke();
            };

            // connect
            clientConnection.Connect(address, Port);

            // configure connection for max scale
            ConfigureKcpConnection(clientConnection);
        }
Esempio n. 3
0
        /// <summary>
        /// Processes a message's data payload.
        /// </summary>
        /// <param name="sourcePacket">The ENET Source packet.</param>
        /// <param name="serverInvoke">Is this intended to be invoked on the server instance?</param>
        /// <param name="connectionID">If it is intended to be invoked on the server, what connection ID to pass to Mirror?</param>
        public void NewMessageDataProcessor(Packet sourcePacket, bool serverInvoke = false, int connectionID = 0)
        {
            if (m_TransportVerbosity == TransportVerbosity.Paranoid)
            {
                Log($"Ignorance Transport: Processing a {sourcePacket.Length} byte payload.");
            }

            // This will be improved on at a later date.
            byte[] dataBuf = new byte[sourcePacket.Length];
            // Copy our data into our buffers from ENET Native -> Ignorance Transport Managed world.
            sourcePacket.CopyTo(dataBuf);
            sourcePacket.Dispose();

            if (m_TransportVerbosity == TransportVerbosity.LogSpam)
            {
                Log($"Ignorance Transport: Oi Mirror, data's arrived! Packet payload:\n{ BitConverter.ToString(dataBuf) }");
            }

            // Invoke the server if we're supposed to.
            if (serverInvoke)
            {
                OnServerDataReceived.Invoke(connectionID, dataBuf);
            }
            else
            {
                // Poke Mirror instead.
                OnClientDataReceived.Invoke(dataBuf);
            }
        }
Esempio n. 4
0
        // segment is valid until function returns.
        void OnLibuvClientMessage(TcpStream handle, ArraySegment <byte> segment)
        {
            //Debug.Log("libuv cl: data=" + BitConverter.ToString(segment.Array, segment.Offset, segment.Count));

            // Mirror event
            OnClientDataReceived.Invoke(segment, Channels.Reliable);
        }
Esempio n. 5
0
        public WebsocketTransport()
        {
            // dispatch the events from the server
            server.Connected     += (connectionId) => OnServerConnected.Invoke(connectionId);
            server.Disconnected  += (connectionId) => OnServerDisconnected.Invoke(connectionId);
            server.ReceivedData  += (connectionId, data) => OnServerDataReceived.Invoke(connectionId, data);
            server.ReceivedError += (connectionId, error) => OnServerError.Invoke(connectionId, error);

            // dispatch events from the client
            client.Connected     += () => OnClientConnected.Invoke();
            client.Disconnected  += () => OnClientDisconnected.Invoke();
            client.ReceivedData  += (data) => OnClientDataReceived.Invoke(data);
            client.ReceivedError += (error) => OnClientError.Invoke(error);

            // configure
            client.NoDelay = NoDelay;
            server.NoDelay = NoDelay;

            // HLAPI's local connection uses hard coded connectionId '0', so we
            // need to make sure that external connections always start at '1'
            // by simple eating the first one before the server starts
            Server.NextConnectionId();

            Debug.Log("Websocket transport initialized!");
        }
Esempio n. 6
0
        // messages should always be processed in early update
        public override void ClientEarlyUpdate()
        {
            // note: process even if not connected because when calling
            // Disconnect, we add a Disconnected event which still needs to be
            // processed here.
            while (clientIncoming.Count > 0)
            {
                Message message = clientIncoming.Dequeue();
                switch (message.eventType)
                {
                case EventType.Connected:
                    Debug.Log("MemoryTransport Client Message: Connected");
                    // event might be null in tests if no NetworkClient is used.
                    OnClientConnected?.Invoke();
                    break;

                case EventType.Data:
                    Debug.Log($"MemoryTransport Client Message: Data: {BitConverter.ToString(message.data)}");
                    // event might be null in tests if no NetworkClient is used.
                    OnClientDataReceived?.Invoke(new ArraySegment <byte>(message.data), 0);
                    break;

                case EventType.Disconnected:
                    Debug.Log("MemoryTransport Client Message: Disconnected");
                    // event might be null in tests if no NetworkClient is used.
                    OnClientDisconnected?.Invoke();
                    break;
                }
            }
        }
        private void RegisterMirrorEvents()
        {
            // Server
            _svConnected    = (id) => OnServerConnected?.Invoke(id);
            _svDisconnected = (id) => OnServerDisconnected?.Invoke(id);
            _svDataReceived = (id, data) => OnServerDataReceived?.Invoke(id, new ArraySegment <byte>(data));
            _svError        = (id, exception) => OnServerError?.Invoke(id, exception);

            Server.OnConnected    += _svConnected;
            Server.OnDisconnected += _svDisconnected;
            Server.OnDataReceived += _svDataReceived;
            Server.OnError        += _svError;

            // Client
            _clConnected    = () => OnClientConnected?.Invoke();
            _clDisconnected = () => OnClientDisconnected?.Invoke();
            _clDataReceived = (data) => OnClientDataReceived?.Invoke(new ArraySegment <byte>(data));
            _clError        = (exception) => OnClientError?.Invoke(exception);

            Client.OnConnected    += _clConnected;
            Client.OnDisconnected += _clDisconnected;
            Client.OnDataReceived += _clDataReceived;
            Client.OnError        += _clError;

            _eventsRegistered = true;
        }
Esempio n. 8
0
        bool ProcessClientMessage()
        {
            if (client.GetNextMessage(out Telepathy.Message message))
            {
                switch (message.eventType)
                {
                case Telepathy.EventType.Connected:
                    OnClientConnected.Invoke();
                    break;

                case Telepathy.EventType.Data:
                    OnClientDataReceived.Invoke(new ArraySegment <byte>(message.data), Channels.DefaultReliable);
                    break;

                case Telepathy.EventType.Disconnected:
                    OnClientDisconnected.Invoke();
                    break;

                default:
                    // TODO:  Telepathy does not report errors at all
                    // it just disconnects,  should be fixed
                    OnClientDisconnected.Invoke();
                    break;
                }
                return(true);
            }
            return(false);
        }
Esempio n. 9
0
        private bool ProcessClientMessage()
        {
            if (m_ClientConn == null)
            {
                return(false);
            }

            if (m_ClientConn.Disposed || !m_ClientConn.Server.IsConnection)
            {
                DisposeClient();
                OnClientDisconnected?.Invoke();
                return(false);
            }

            bool    receive = false;
            Message msg     = default;

            try
            {
                receive = m_ClientConn.TryReadMessage(out msg);
            }
            catch (Exception ex)
            {
                OnClientError?.Invoke(ex);
            }

            if (receive)
            {
                OnClientDataReceived?.Invoke(new ArraySegment <byte>(msg.ToArray()), msg.Channel);
            }
            return(receive);
        }
Esempio n. 10
0
        private bool ProcessClientMessages()
        {
            while (MirrorClientIncomingQueue.TryDequeue(out IncomingPacket pkt))
            {
                switch (pkt.type)
                {
                case MirrorPacketType.ClientConnected:
                    if (DebugEnabled)
                    {
                        print($"Ignorance: We have connected!");
                    }
                    isClientConnected = true;
                    OnClientConnected?.Invoke();
                    break;

                case MirrorPacketType.ClientDisconnected:
                    if (DebugEnabled)
                    {
                        print($"Ignorance: We have been disconnected.");
                    }
                    isClientConnected = false;
                    OnClientDisconnected?.Invoke();
                    break;

                case MirrorPacketType.ClientGotData:
                    OnClientDataReceived?.Invoke(new ArraySegment <byte>(pkt.data));
                    break;
                }
            }
            return(true);
        }
Esempio n. 11
0
        bool ProcessClientMessage()
        {
            Telepathy.Message message;
            if (client.GetNextMessage(out message))
            {
                switch (message.eventType)
                {
                // convert Telepathy EventType to TransportEvent
                case Telepathy.EventType.Connected:
                    OnClientConnected.Invoke();
                    break;

                case Telepathy.EventType.Data:
                    OnClientDataReceived.Invoke(message.data);
                    break;

                case Telepathy.EventType.Disconnected:
                    OnClientDisconnected.Invoke();
                    break;

                default:
                    // TODO:  Telepathy does not report errors at all
                    // it just disconnects,  should be fixed
                    OnClientDisconnected.Invoke();
                    break;
                }
                return(true);
            }
            return(false);
        }
Esempio n. 12
0
        void Awake()
        {
            // logging
            if (debugLog)
            {
                Log.Info = Debug.Log;
            }
            Log.Warning = Debug.LogWarning;
            Log.Error   = Debug.LogError;

            // TODO simplify after converting Mirror Transport events to Action
            client = new KcpClient(
                () => OnClientConnected.Invoke(),
                (message) => OnClientDataReceived.Invoke(message, Channels.DefaultReliable),
                () => OnClientDisconnected.Invoke()
                );
            // TODO simplify after converting Mirror Transport events to Action
            server = new KcpServer(
                (connectionId) => OnServerConnected.Invoke(connectionId),
                (connectionId, message) => OnServerDataReceived.Invoke(connectionId, message, Channels.DefaultReliable),
                (connectionId) => OnServerDisconnected.Invoke(connectionId),
                NoDelay,
                Interval,
                FastResend,
                CongestionWindow,
                SendWindowSize,
                ReceiveWindowSize
                );
            Debug.Log("KcpTransport initialized!");
        }
        public override void Awake()
        {
            KCPConfig conf = new KCPConfig();

            if (!File.Exists("KCPConfig.json"))
            {
                File.WriteAllText("KCPConfig.json", JsonConvert.SerializeObject(conf, Formatting.Indented));
            }
            else
            {
                conf = JsonConvert.DeserializeObject <KCPConfig>(File.ReadAllText("KCPConfig.json"));
            }

            NoDelay           = conf.NoDelay;
            Interval          = conf.Interval;
            FastResend        = conf.FastResend;
            CongestionWindow  = conf.CongestionWindow;
            SendWindowSize    = conf.SendWindowSize;
            ReceiveWindowSize = conf.ReceiveWindowSize;
            ConnectionTimeout = conf.ConnectionTimeout;

            // logging
            //   Log.Info should use Debug.Log if enabled, or nothing otherwise
            //   (don't want to spam the console on headless servers)
            if (debugLog)
            {
                Log.Info = Console.WriteLine;
            }
            else
            {
                Log.Info = _ => { }
            };
            Log.Warning = Console.WriteLine;
            Log.Error   = Console.WriteLine;

            // client
            client = new KcpClient(
                () => OnClientConnected.Invoke(),
                (message) => OnClientDataReceived.Invoke(message, 0),
                () => OnClientDisconnected.Invoke()
                );

            // server
            server = new KcpServer(
                (connectionId) => OnServerConnected.Invoke(connectionId),
                (connectionId, message) => OnServerDataReceived.Invoke(connectionId, message, 0),
                (connectionId) => OnServerDisconnected.Invoke(connectionId),
                NoDelay,
                Interval,
                FastResend,
                CongestionWindow,
                SendWindowSize,
                ReceiveWindowSize
                );


            Console.WriteLine("KcpTransport initialized!");
        }
Esempio n. 14
0
 private void LobbyManager_OnNetworkMessage(long lobbyId, long userId, byte channelId, byte[] data)
 {
     if (ServerActive())
     {
         OnServerDataReceived?.Invoke(clients.GetByFirst(userId), new ArraySegment <byte>(data), channelId);
     }
     else if (userId == currentLobby.OwnerId)
     {
         OnClientDataReceived?.Invoke(new ArraySegment <byte>(data), channelId);
     }
 }
    public void DirectReceiveData(ArraySegment <byte> data, int channel, int clientID = -1)
    {
        if (isServer)
        {
            OnServerDataReceived?.Invoke(connectedDirectClients.GetByFirst(clientID), new ArraySegment <byte>(data.Array, 0, data.Count), channel);
        }

        if (isClient)
        {
            OnClientDataReceived?.Invoke(data, channel);
        }
    }
Esempio n. 16
0
        public override void OnAwake()
        {
            base.OnAwake();
            // create client & server
            client = new Telepathy.Client(clientMaxMessageSize);
            server = new Telepathy.Server(serverMaxMessageSize);

            // tell Telepathy to use Unity's Debug.Log
            Telepathy.Log.Info    = Debug.Log;
            Telepathy.Log.Warning = Debug.LogWarning;
            Telepathy.Log.Error   = Debug.LogError;

            // client hooks
            // other systems hook into transport events in OnCreate or
            // OnStartRunning in no particular order. the only way to avoid
            // race conditions where telepathy uses OnConnected before another
            // system's hook (e.g. statistics OnData) was added is to wrap
            // them all in a lambda and always call the latest hook.
            // (= lazy call)
            client.OnConnected    = () => OnClientConnected.Invoke();
            client.OnData         = (segment) => OnClientDataReceived.Invoke(segment, Channels.DefaultReliable);
            client.OnDisconnected = () => OnClientDisconnected.Invoke();

            // client configuration
            client.NoDelay           = NoDelay;
            client.SendTimeout       = SendTimeout;
            client.ReceiveTimeout    = ReceiveTimeout;
            client.SendQueueLimit    = clientSendQueueLimit;
            client.ReceiveQueueLimit = clientReceiveQueueLimit;

            // server hooks
            // other systems hook into transport events in OnCreate or
            // OnStartRunning in no particular order. the only way to avoid
            // race conditions where telepathy uses OnConnected before another
            // system's hook (e.g. statistics OnData) was added is to wrap
            // them all in a lambda and always call the latest hook.
            // (= lazy call)
            server.OnConnected    = (connectionId) => OnServerConnected.Invoke(connectionId);
            server.OnData         = (connectionId, segment) => OnServerDataReceived.Invoke(connectionId, segment, Channels.DefaultReliable);
            server.OnDisconnected = (connectionId) => OnServerDisconnected.Invoke(connectionId);

            // server configuration
            server.NoDelay           = NoDelay;
            server.SendTimeout       = SendTimeout;
            server.ReceiveTimeout    = ReceiveTimeout;
            server.SendQueueLimit    = serverSendQueueLimitPerConnection;
            server.ReceiveQueueLimit = serverReceiveQueueLimitPerConnection;

            // allocate enabled check only once
            enabledCheck = () => Enabled;

            Debug.Log("TelepathyTransport initialized!");
        }
Esempio n. 17
0
 private void Client_onData(ArraySegment <byte> data, int channel)
 {
     if (enabled)
     {
         OnClientDataReceived.Invoke(data, channel);
     }
     else
     {
         clientDisabledQueue.Enqueue(new ClientDataMessage(data, channel));
         checkMessageQueues = true;
     }
 }
Esempio n. 18
0
File: Monke.cs Progetto: dededec/TFG
    private void OnClientDataReceive(ArraySegment <byte> data, int channel)
    {
        try
        {
            var rawData = data.Array;
            int pos     = data.Offset;

            OpCodes opcode = (OpCodes)rawData.ReadByte(ref pos);

            switch (opcode)
            {
            case OpCodes.ServerPublicKey:
                _serverPublicKey = rawData.ReadBytes(ref pos);

                pos = 0;
                _clientSendBuffer.WriteByte(ref pos, (byte)OpCodes.ClientPublicKey);
                _clientSendBuffer.WriteBytes(ref pos, _keyPair.PublicKey);
                CommunicationTransport.ClientSend(Channels.Reliable, new ArraySegment <byte>(_clientSendBuffer, 0, pos));

                if (showDebugLogs)
                {
                    Debug.Log($"<color=green>MONKE | CLIENT RECIEVED SERVER PUBLIC KEY!</color>");
                }

                OnClientConnected?.Invoke();

                break;

            case OpCodes.Data:
                _readBuffer = rawData.ReadBytes(ref pos);
                _nonce      = rawData.ReadBytes(ref pos);

                _encryptionBuffer = PublicKeyBox.Open(_readBuffer, _nonce, _keyPair.PrivateKey, _serverPublicKey);
                OnClientDataReceived?.Invoke(new ArraySegment <byte>(_encryptionBuffer), channel);


                if (showDebugLogs)
                {
                    Debug.Log($"<color=green>MONKE | CLIENT DATA | RAW DATA: " + _readBuffer.Length + " DECRYPTED DATA LENGTH: " + _encryptionBuffer.Length + "</color>" +
                              " <color=yellow>DELTA: " + (_readBuffer.Length - _encryptionBuffer.Length) + "</color>");
                }

                break;
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Error: " + e);
        }
    }
Esempio n. 19
0
        private void Client_onData(ArraySegment <byte> data, DeliveryMethod deliveryMethod)
        {
            int channel = channels.IndexOf(deliveryMethod);

            if (enabled)
            {
                OnClientDataReceived.Invoke(data, channel);
            }
            else
            {
                clientDisabledQueue.Enqueue(new ClientDataMessage(data, channel));
                checkMessageQueues = true;
            }
        }
Esempio n. 20
0
        public override void OnAwake()
        {
            base.OnAwake();
            // logging
            //   Log.Info should use Debug.Log if enabled, or nothing otherwise
            //   (don't want to spam the console on headless servers)
            if (debugLog)
            {
                Log.Info = Debug.Log;
            }
            else
            {
                Log.Info = _ => {}
            };
            Log.Warning = Debug.LogWarning;
            Log.Error   = Debug.LogError;

            // client
            client = new KcpClient(
                () => OnClientConnected.Invoke(),
                (message) => OnClientDataReceived.Invoke(message, Channels.DefaultReliable),
                () => OnClientDisconnected.Invoke()
                );

            // server
            server = new KcpServer(
                (connectionId) => OnServerConnected.Invoke(connectionId),
                (connectionId, message) => OnServerDataReceived.Invoke(connectionId, message, Channels.DefaultReliable),
                (connectionId) => OnServerDisconnected.Invoke(connectionId),
                NoDelay,
                Interval,
                FastResend,
                CongestionWindow,
                SendWindowSize,
                ReceiveWindowSize
                );

            if (statisticsLog)
            {
                Task.Run(async() => {
                    await Task.Delay(100);
                    OnLogStatistics();
                    await Task.Delay(100);
                });
                //InvokeRepeating(nameof(OnLogStatistics), 1, 1);
            }


            Debug.Log("KcpTransport initialized!");
        }
Esempio n. 21
0
        public static void Init(bool isServer = false, bool isClient = false, bool isSimulated = false)
        {
            IsServer    = isServer ? true : IsServer;
            IsClient    = isClient ? true : IsClient;
            IsSimulated = isSimulated ? true : IsSimulated;

            if (isSimulated)
            {
                if (NetLogFilter.logInfo)
                {
                    Debug.Log("Transport Layer Initialized: Simulation");
                }
                return;
            }

            if (IsServer && server == null)
            {
                // server
                server = new KcpServer(
                    (connectionId) => OnServerConnected.Invoke(connectionId),
                    (connectionId, message) => OnServerDataReceived.Invoke(connectionId, message, (int)UDPChannels.Reliable),
                    (connectionId) => OnServerDisconnected.Invoke(connectionId),
                    NoDelay,
                    Interval,
                    FastResend,
                    CongestionWindow,
                    SendWindowSize,
                    ReceiveWindowSize
                    );
                if (NetLogFilter.logInfo)
                {
                    Debug.Log("Transport Layer Initialized: Server");
                }
            }

            if (IsClient && client == null)
            {
                // client
                client = new KcpClient(
                    () => OnClientConnected.Invoke(),
                    (message) => OnClientDataReceived.Invoke(message, (int)UDPChannels.Reliable),
                    () => OnClientDisconnected.Invoke()
                    );
                if (NetLogFilter.logInfo)
                {
                    Debug.Log("Transport Layer Initialized: Client");
                }
            }
        }
Esempio n. 22
0
        public bool ProcessClientMessage()
        {
            if (clientId == -1)
            {
                return(false);
            }

            int connectionId;
            int channel;
            int receivedSize;
            NetworkEventType networkEvent = NetworkTransport.ReceiveFromHost(clientId, out connectionId, out channel, clientReceiveBuffer, clientReceiveBuffer.Length, out receivedSize, out error);

            // note: 'error' is used for extra information, e.g. the reason for
            // a disconnect. we don't necessarily have to throw an error if
            // error != 0. but let's log it for easier debugging.
            //
            // DO NOT return after error != 0. otherwise Disconnect won't be
            // registered.
            NetworkError networkError = (NetworkError)error;

            if (networkError != NetworkError.Ok)
            {
                string message = "NetworkTransport.Receive failed: hostid=" + clientId + " connId=" + connectionId + " channelId=" + channel + " error=" + networkError;
                OnClientError.Invoke(new Exception(message));
            }

            // raise events
            switch (networkEvent)
            {
            case NetworkEventType.ConnectEvent:
                OnClientConnected.Invoke();
                break;

            case NetworkEventType.DataEvent:
                byte[] data = new byte[receivedSize];
                Array.Copy(clientReceiveBuffer, data, receivedSize);
                OnClientDataReceived.Invoke(data);
                break;

            case NetworkEventType.DisconnectEvent:
                OnClientDisconnected.Invoke();
                break;

            default:
                return(false);
            }

            return(true);
        }
Esempio n. 23
0
        public SteamworksTransport()
        {
            _client = new P2PClient();
            _server = new P2PServer();

            _client.OnConnected.AddListener(() => OnClientConnected?.Invoke());
            _client.OnData.AddListener(bytes => { OnClientDataReceived?.Invoke(bytes); });
            _client.OnError.AddListener(exception => { OnClientError?.Invoke(exception); });
            _client.OnDisconnect.AddListener(() => { OnClientDisconnected?.Invoke(); });

            _server.OnConnect.AddListener(id => { OnServerConnected?.Invoke(id); });
            _server.OnData.AddListener((id, data) => { OnServerDataReceived?.Invoke(id, data); });
            _server.OnError.AddListener((id, exception) => { OnServerError?.Invoke(id, exception); });
            _server.OnDisconnect.AddListener(id => { OnServerDisconnected?.Invoke(id); });
        }
Esempio n. 24
0
        private void ProcessClientQueue()
        {
            int processedCount = 0;

            while (
                enabled &&
                processedCount < clientMaxMessagesPerTick &&
                clientDisabledQueue.Count > 0
                )
            {
                processedCount++;

                ClientDataMessage data = clientDisabledQueue.Dequeue();
                OnClientDataReceived.Invoke(data.data, data.channel);
            }
        }
        public FizzySteamyMirror()
        {
            // dispatch the events from the server
            server.OnConnected     += (id) => OnServerConnected?.Invoke(id);
            server.OnDisconnected  += (id) => OnServerDisconnected?.Invoke(id);
            server.OnReceivedData  += (id, data, channel) => OnServerDataReceived?.Invoke(id, new ArraySegment <byte>(data), channel);
            server.OnReceivedError += (id, exception) => OnServerError?.Invoke(id, exception);

            // dispatch events from the client
            client.OnConnected     += () => OnClientConnected?.Invoke();
            client.OnDisconnected  += () => OnClientDisconnected?.Invoke();
            client.OnReceivedData  += (data, channel) => OnClientDataReceived?.Invoke(new ArraySegment <byte>(data), channel);
            client.OnReceivedError += (exception) => OnClientError?.Invoke(exception);

            Debug.Log("FizzySteamyMirror initialized!");
        }
Esempio n. 26
0
        bool ProcessClientMessage()
        {
            if (client.GetNextMessage(out Telepathy.Message message))
            {
                switch (message.eventType)
                {
                case Telepathy.EventType.Connected:
                    OnClientConnected.Invoke();
                    break;

                case Telepathy.EventType.Data:
#if UNITY_EDITOR
                    if (clientSimulatedDelay > 0)
                    {
                        StartCoroutine(_DelayDispatchClientData(clientSimulatedDelay, message));
                    }
                    else
#endif
                    OnClientDataReceived.Invoke(new ArraySegment <byte>(message.data), Channels.DefaultReliable);
                    break;

                case Telepathy.EventType.Disconnected:
                    // Wappen: I dont want to modify OnClientDisconnected event type,
                    // error message will have to tug in here, before firing disconnect message
                    if (message.data != null)
                    {
                        Common.WappenDeserializeDisconnectMessage(message.data, out ClientLastErrorMessage);
                    }
                    else
                    {
                        // Something irrelevent, I just pick some SocketError
                        ClientLastErrorMessage = "Unknown disconnect.";
                    }
                    OnClientDisconnected.Invoke();
                    break;

                default:
                    // TODO:  Telepathy does not report errors at all
                    // it just disconnects,  should be fixed
                    OnClientDisconnected.Invoke();
                    break;
                }
                return(true);
            }
            return(false);
        }
Esempio n. 27
0
        private void NATP_OnReceived(EndPoint endpoint, byte[] buffer, long offset, long size)
        {
            if (usingSTUN) // serve as server
            {
                stunCore.OnResponse(buffer, offset, size);
            }
            else // serve as client
            {
                // check if data is heartbeat
                if (IsServerHeartbeat(buffer, offset, size))
                {
                    lock (_lockHeartbeat)
                    {
                        if (receivedHeartBeatCount == long.MaxValue)
                        {
                            receivedHeartBeatCount = 0;
                        }
                        else
                        {
                            receivedHeartBeatCount++;
                        }
                    }
                    // if it's fisrt time receive the heartbeat from server, means connect to server.
                    if (!IsConnectedToHost)
                    {
                        IsConnectedToHost = true;
                        StartHeartbeatTimer(HeartbeatAfterConnected);
                        //OnClientConnected?.BeginInvoke(this, EventArgs.Empty, EndAsyncEvent, null);
                        OnClientConnected?.Invoke(this, EventArgs.Empty);
                    }
                }

                /* else if (IsServerDisconnectHeartbeat(buffer, offset, size))
                 * {
                 *   DisconnectAndStop();
                 * }*/
                else // normal data
                {
                    byte[] pureData = new byte[size];
                    Array.Copy(buffer, offset, pureData, 0, size);
                    OnClientDataReceived?.Invoke(this, new NATP_STUN_ClientDataReceivedEventArgs(new ArraySegment <byte>(pureData, 0, (int)size)));
                    //OnClientDataReceived?.BeginInvoke(this, new STUN_ClientDataReceivedEventArgs(new ArraySegment<byte>(pureData, 0, (int)size)), EndAsyncEvent, null);
                }
            }
        }
Esempio n. 28
0
        private async void AcceptClients()
        {
            listener.Start();
            while (!runtimeToken.IsCancellationRequested)
            {
                TcpClient client = await listener.AcceptTcpClientAsync();

                NetworkStream     clientStream = client.GetStream();
                NetworkConnection connection   = new NetworkConnection(ref clientStream, (IPEndPoint)client.Client.RemoteEndPoint);
                connection.OnDisconnected += (x, y) => OnClientDisconnected?.Invoke(x, y);
                connection.OnDisconnected += (x, y) => { connectedClients.Remove(x); x.Shutdown(); };
                connection.OnError        += (x, y) => OnClientError?.Invoke(x, y);
                connection.OnReceived     += (x, y) => OnClientDataReceived?.Invoke(x, y);
                OnClientConnected?.Invoke(connection, null);
                connectedClients.Add(connection);
            }
            listener.Stop();
        }
        public WebsocketTransport()
        {
            // dispatch the events from the server
            server.Connected     += (connectionId) => OnServerConnected.Invoke(connectionId);
            server.Disconnected  += (connectionId) => OnServerDisconnected.Invoke(connectionId);
            server.ReceivedData  += (connectionId, data) => OnServerDataReceived.Invoke(connectionId, data, Channels.DefaultReliable);
            server.ReceivedError += (connectionId, error) => OnServerError.Invoke(connectionId, error);

            // dispatch events from the client
            client.Connected     += () => OnClientConnected.Invoke();
            client.Disconnected  += () => OnClientDisconnected.Invoke();
            client.ReceivedData  += (data) => OnClientDataReceived.Invoke(data, Channels.DefaultReliable);
            client.ReceivedError += (error) => OnClientError.Invoke(error);

            // configure
            client.NoDelay = NoDelay;
            server.NoDelay = NoDelay;
        }
Esempio n. 30
0
        void Awake()
        {
            // logging
            //   Log.Info should use Debug.Log if enabled, or nothing otherwise
            //   (don't want to spam the console on headless servers)
            if (debugLog)
            {
                Log.Info = Debug.Log;
            }
            else
            {
                Log.Info = _ => {}
            };
            Log.Warning = Debug.LogWarning;
            Log.Error   = Debug.LogError;

            // client
            client = new KcpClient(
                () => OnClientConnected.Invoke(),
                (message) => OnClientDataReceived.Invoke(message, Channels.DefaultReliable),
                () => OnClientDisconnected.Invoke()
                );

            // server
            server = new KcpServer(
                (connectionId) => OnServerConnected.Invoke(connectionId),
                (connectionId, message) => OnServerDataReceived.Invoke(connectionId, message, Channels.DefaultReliable),
                (connectionId) => OnServerDisconnected.Invoke(connectionId),
                NoDelay,
                Interval,
                FastResend,
                CongestionWindow,
                SendWindowSize,
                ReceiveWindowSize
                );

            // scene change message will disable transports.
            // kcp processes messages in an internal loop which should be
            // stopped immediately after scene change (= after disabled)
            client.OnCheckEnabled = () => enabled;
            server.OnCheckEnabled = () => enabled;

            Debug.Log("KcpTransport initialized!");
        }