示例#1
0
        // messages should always be processed in early update
        public override void ServerEarlyUpdate()
        {
            while (serverIncoming.Count > 0)
            {
                Message message = serverIncoming.Dequeue();
                switch (message.eventType)
                {
                case EventType.Connected:
                    Debug.Log("MemoryTransport Server Message: Connected");
                    // event might be null in tests if no NetworkClient is used.
                    OnServerConnected?.Invoke(message.connectionId);
                    break;

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

                case EventType.Disconnected:
                    Debug.Log("MemoryTransport Server Message: Disconnected");
                    // event might be null in tests if no NetworkClient is used.
                    OnServerDisconnected?.Invoke(message.connectionId);
                    break;
                }
            }
        }
        void InitServer()
        {
            recipientsCache = new List <int> [transports.Length];

            // wire all the base transports to my events
            for (int i = 0; i < transports.Length; i++)
            {
                recipientsCache[i] = new List <int>();

                // this is required for the handlers,  if I use i directly
                // then all the handlers will use the last i
                int       locali    = i;
                Transport transport = transports[i];

                transport.OnServerConnected.AddListener(baseConnectionId =>
                {
                    OnServerConnected.Invoke(FromBaseId(locali, baseConnectionId));
                });

                transport.OnServerDataReceived.AddListener((baseConnectionId, data, channel) =>
                {
                    OnServerDataReceived.Invoke(FromBaseId(locali, baseConnectionId), data, channel);
                });

                transport.OnServerError.AddListener((baseConnectionId, error) =>
                {
                    OnServerError.Invoke(FromBaseId(locali, baseConnectionId), error);
                });
                transport.OnServerDisconnected.AddListener(baseConnectionId =>
                {
                    OnServerDisconnected.Invoke(FromBaseId(locali, baseConnectionId));
                });
            }
        }
        void ProcessErlangenMessage(byte[] message)
        {
            // check first byte: 1 = connected, 2 = disconnected, 3 = data
            if (message.Length == 5 && message[0] == 0x01)
            {
                // extract connectionId
                int connectionId = BytesToIntBigEndian(message, 1);
                OnServerConnected.Invoke(connectionId);
                //Debug.Log("Booster: client connected. connId=" + connectionId);
            }
            else if (message.Length == 5 && message[0] == 0x02)
            {
                // extract connectionId
                int connectionId = BytesToIntBigEndian(message, 1);
                OnServerDisconnected.Invoke(connectionId);
                //Debug.Log("Booster: client disconnected. connId=" + connectionId);
            }
            else if (message.Length >= 5 && message[0] == 0x03)
            {
                // extract connectionId
                int connectionId = BytesToIntBigEndian(message, 1);

                // create data segment
                int dataOffset = 1 + 4; // type=1, connectionid=4
                int dataLength = message.Length - dataOffset;
                ArraySegment <byte> segment = new ArraySegment <byte>(message, dataOffset, dataLength);
                OnServerDataReceived.Invoke(connectionId, segment, Channels.DefaultReliable);
                //Debug.Log("Booster: client data. connId=" + connectionId + " data=" + BitConverter.ToString(segment, segment.Offset, segment.Count));
            }
            else
            {
                Debug.LogWarning("Booster: parse failed: " + BitConverter.ToString(message));
            }
        }
示例#4
0
        // Server processing loop.
        private bool ProcessServerMessages()
        {
            // Get to the queue! Check those corners!
            while (MirrorServerIncomingQueue.TryDequeue(out IncomingPacket pkt))
            {
                switch (pkt.type)
                {
                case MirrorPacketType.ServerClientConnected:
                    OnServerConnected?.Invoke(pkt.connectionId);
                    break;

                case MirrorPacketType.ServerClientDisconnected:
                    OnServerDisconnected?.Invoke(pkt.connectionId);
                    break;

                case MirrorPacketType.ServerClientSentData:
                    OnServerDataReceived?.Invoke(pkt.connectionId, new ArraySegment <byte>(pkt.data), pkt.channelId);
                    break;

                default:
                    // Nothing to see here.
                    break;
                }
            }

            // Flashbang though the window and race to the finish.
            return(true);
        }
示例#5
0
        // Server processing loop.
        private bool ProcessServerMessages()
        {
            // Get to the queue! Check those corners!
            while (MirrorServerIncomingQueue.TryDequeue(out IncomingPacket pkt))
            {
                switch (pkt.type)
                {
                case MirrorPacketType.ServerClientConnected:
                    OnServerConnected?.Invoke(pkt.connectionId);
                    break;

                case MirrorPacketType.ServerClientDisconnected:
                    OnServerDisconnected?.Invoke(pkt.connectionId);
                    break;

                case MirrorPacketType.ServerClientSentData:
                    OnServerDataReceived?.Invoke(pkt.connectionId, new ArraySegment <byte>(pkt.data), pkt.channelId);
                    break;

                default:
                    // Nothing to see here.
                    break;
                }

                // Some messages can disable the transport
                // If the transport was disabled by any of the messages, we have to break out of the loop and wait until we've been re-enabled.
                if (!enabled)
                {
                    break;
                }
            }

            // Flashbang though the window and race to the finish.
            return(true);
        }
        public override void ServerStart()
        {
            // create server
            server = new Telepathy.Server(serverMaxMessageSize);

            // 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.Reliable);
            server.OnDisconnected = (connectionId) => OnServerDisconnected.Invoke(connectionId);

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

            server.Start(port);
        }
示例#7
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!");
        }
示例#8
0
        public bool ProcessServerMessage()
        {
            if (server.GetNextMessage(out Telepathy.Message message))
            {
                switch (message.eventType)
                {
                case Telepathy.EventType.Connected:
                    OnServerConnected.Invoke(message.connectionId);
                    break;

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

                case Telepathy.EventType.Disconnected:
                    OnServerDisconnected.Invoke(message.connectionId);
                    break;

                default:
                    // TODO handle errors from Telepathy when telepathy can report errors
                    OnServerDisconnected.Invoke(message.connectionId);
                    break;
                }
                return(true);
            }
            return(false);
        }
        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;
        }
示例#10
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);
            }
        }
示例#11
0
        // Server processing loop.
        private bool ProcessServerMessages()
        {
            // Get to the queue! Check those corners!
            while (MirrorIncomingQueue.TryDequeue(out IncomingPacket pkt))
            {
                // print($"Firing a packet with type: {pkt.type} for connection ID: {pkt.connectionId}\n{(pkt.data == null ? "NO DATA" : BitConverter.ToString(pkt.data))}");
                switch (pkt.type)
                {
                case MirrorPacketType.ServerClientConnected:
                    OnServerConnected?.Invoke(pkt.connectionId);
                    break;

                case MirrorPacketType.ServerClientDisconnected:
                    OnServerDisconnected?.Invoke(pkt.connectionId);
                    break;

                case MirrorPacketType.ServerClientSentData:
                    OnServerDataReceived?.Invoke(pkt.connectionId, new ArraySegment <byte>(pkt.data));
                    break;

                default:
                    // Nothing to see here.
                    break;
                }
            }

            // Flashbang though the window and race to the finish.
            return(true);
        }
        public void ProcessServerMessages()
        {
            if (server.Active)
            {
                server.GetNextMessages(queue);
                while (queue.Count > 0)
                {
                    Apathy.Message message = queue.Dequeue();
                    switch (message.eventType)
                    {
                    case Apathy.EventType.Connected:
                        OnServerConnected.Invoke(message.connectionId);
                        break;     // breaks switch, not while

                    case Apathy.EventType.Data:
                        OnServerDataReceived.Invoke(message.connectionId, message.data, Channels.DefaultReliable);
                        break;     // breaks switch, not while

                    case Apathy.EventType.Disconnected:
                        OnServerDisconnected.Invoke(message.connectionId);
                        break;     // breaks switch, not while
                    }
                }
            }
        }
示例#13
0
        public bool ProcessServerMessage()
        {
            Telepathy.Message message;
            if (server.GetNextMessage(out message))
            {
                switch (message.eventType)
                {
                // convert Telepathy EventType to TransportEvent
                case Telepathy.EventType.Connected:
                    OnServerConnected.Invoke(message.connectionId);
                    break;

                case Telepathy.EventType.Data:
                    OnServerDataReceived.Invoke(message.connectionId, message.data);
                    break;

                case Telepathy.EventType.Disconnected:
                    OnServerDisconnected.Invoke(message.connectionId);
                    break;

                default:
                    // TODO handle errors from Telepathy when telepathy can report errors
                    OnServerDisconnected.Invoke(message.connectionId);
                    break;
                }
                return(true);
            }
            return(false);
        }
示例#14
0
        void AddServerCallbacks()
        {
            // wire all the base transports to my events
            for (int i = 0; i < transports.Length; i++)
            {
                // this is required for the handlers,  if I use i directly
                // then all the handlers will use the last i
                int       locali    = i;
                Transport transport = transports[i];

                transport.OnServerConnected = (baseConnectionId =>
                {
                    OnServerConnected.Invoke(FromBaseId(locali, baseConnectionId));
                });

                transport.OnServerDataReceived = (baseConnectionId, data, channel) =>
                {
                    OnServerDataReceived.Invoke(FromBaseId(locali, baseConnectionId), data, channel);
                };

                transport.OnServerError = (baseConnectionId, error) =>
                {
                    OnServerError.Invoke(FromBaseId(locali, baseConnectionId), error);
                };
                transport.OnServerDisconnected = baseConnectionId =>
                {
                    OnServerDisconnected.Invoke(FromBaseId(locali, baseConnectionId));
                };
            }
        }
示例#15
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!");
        }
示例#16
0
        public bool ProcessServerMessage()
        {
            if (serverHostId == -1)
            {
                return(false);
            }

            int connectionId = -1;
            int channel;
            int receivedSize;
            NetworkEventType networkEvent = NetworkTransport.ReceiveFromHost(serverHostId, out connectionId, out channel, serverReceiveBuffer, serverReceiveBuffer.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=" + serverHostId + " connId=" + connectionId + " channelId=" + channel + " error=" + networkError;

                // TODO write a TransportException or better
                OnServerError.Invoke(connectionId, new Exception(message));
            }

            // LLAPI client sends keep alive messages (75-6C-6C) on channel=110.
            // ignore all messages that aren't for our selected channel.

            /*if (channel != channelId)
             * {
             *  return false;
             * }*/

            switch (networkEvent)
            {
            case NetworkEventType.ConnectEvent:
                OnServerConnected.Invoke(connectionId);
                break;

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

            case NetworkEventType.DisconnectEvent:
                OnServerDisconnected.Invoke(connectionId);
                break;

            default:
                // nothing or a message we don't recognize
                return(false);
            }

            return(true);
        }
        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!");
        }
示例#18
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);
        }
    }
示例#20
0
 private void Server_onData(int clientId, ArraySegment <byte> data, int channel)
 {
     if (enabled)
     {
         OnServerDataReceived.Invoke(clientId, data, channel);
     }
     else
     {
         serverDisabledQueue.Enqueue(new ServerDataMessage(clientId, data, channel));
         checkMessageQueues = true;
     }
 }
示例#21
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!");
        }
示例#22
0
 void OnLibuvServerMessage(TcpStream handle, ArraySegment <byte> segment)
 {
     // valid connection?
     if (connections.ContainsKey((int)handle.UserToken))
     {
         // DOTSNET event
         OnServerDataReceived.Invoke((int)handle.UserToken, segment, Channels.Reliable);
     }
     else
     {
         Debug.LogError("libuv sv: invalid connectionid: " + (int)handle.UserToken);
     }
 }
示例#23
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!");
        }
示例#24
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");
                }
            }
        }
示例#25
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); });
        }
示例#26
0
        private void ProcessServerQueue()
        {
            int processedCount = 0;

            while (
                enabled &&
                processedCount < serverMaxMessagesPerTick &&
                serverDisabledQueue.Count > 0
                )
            {
                processedCount++;
                ServerDataMessage data = serverDisabledQueue.Dequeue();
                OnServerDataReceived.Invoke(data.clientId, data.data, data.channel);
            }
        }
示例#27
0
        public bool ProcessServerMessage()
        {
            if (server.GetNextMessage(out Telepathy.Message message))
            {
                switch (message.eventType)
                {
                case Telepathy.EventType.PreConnect:
                    OnServerPreConnect?.Invoke(message.connectionId);
                    break;

                case Telepathy.EventType.Connected:
                    OnServerConnected.Invoke(message.connectionId);
                    break;

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

                case Telepathy.EventType.Disconnected:
                    // Wappen: without modifying OnServerDisconnected signature
                    // I will tug in error to separate field
                    if (message.data != null)
                    {
                        string reason;
                        Common.WappenDeserializeDisconnectMessage(message.data, out reason);

                        bool isAttacker = reason != null && reason.StartsWith("ATK");
                        ServerWriteDisconnectReason(message.connectionId, reason, isAttacker);
                    }
                    OnServerDisconnected.Invoke(message.connectionId);
                    break;

                default:
                    // TODO handle errors from Telepathy when telepathy can report errors
                    OnServerDisconnected.Invoke(message.connectionId);
                    break;
                }
                return(true);
            }
            return(false);
        }
        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!");
        }
示例#29
0
文件: Monke.cs 项目: dededec/TFG
    void OnServerDataReceive(int conn, 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.ClientPublicKey:
                byte[] clientPublicKey = rawData.ReadBytes(ref pos);

                _serverSessions.Add(conn, clientPublicKey);

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

                OnServerConnected?.Invoke(conn);
                break;

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

                if (_serverSessions.ContainsKey(conn))
                {
                    _encryptionBuffer = PublicKeyBox.Open(_readBuffer, _nonce, _keyPair.PrivateKey, _serverSessions[conn]);
                    OnServerDataReceived?.Invoke(conn, new ArraySegment <byte>(_encryptionBuffer), channel);

                    if (showDebugLogs)
                    {
                        Debug.Log($"<color=green>MONKE | SERVER DATA | RAW DATA: " + _readBuffer.Length + " DATA DECRYPTED FROM CONN ID: " + conn + " SIZE: " + _encryptionBuffer.Length + "</color>" +
                                  " <color=yellow>DELTA: " + (_readBuffer.Length - _encryptionBuffer.Length) + "</color>");
                    }
                }
                break;
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Error: " + e);
        }
    }
        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;
        }