Exemple #1
0
    /*
     * +-------------------------+
     * |        Connection       |
     * +-------------------------+
     */

    public virtual int Connect(string address, int port)
    {
        if (this.threadLoop == false)
        {
            CreateThread();
        }

        int  node = -1;
        bool ret  = false;

        try {
            T transport = new T();
            transport.SetServerPort(this.port);
            ret = transport.Connect(address, port);
            if (ret)
            {
                node = JoinSession(transport);
            }
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
        }

        if (this.networkStateHandler != null)
        {
            NetworkState state = new NetworkState();
            state.type   = NetEventType.Connect;
            state.result = (ret)? NetEventResult.Success : NetEventResult.Failure;
            this.networkStateHandler(node, state);
        }

        return(node);
    }
Exemple #2
0
        /// <summary>
        /// Remove a callback from listening for payloads of a given type.
        /// </summary>
        /// <typeparam name="T">The payload type being listened for</typeparam>
        /// <param name="callback">The delegate to remove</param>
        public void RemoveCallback <T>(FlarePayloadCallback <T> callback) where T : INetworkPayload
        {
            if (isInvoking)
            {
                registrationQueue.Enqueue(() => Remove(callback));
            }
            else
            {
                Remove(callback);
            }

            void Remove <P>(FlarePayloadCallback <P> c) where P : INetworkPayload
            {
                var tag = NetworkTagAttribute.GetTag(typeof(P));

                // Remove the callback from the dictionary
                if (tag != null)
                {
                    if (payloadCallbacks.TryGetValue(tag.Value, out var value))
                    {
                        value.Remove(c);
                    }
                    else
                    {
                        NetworkLogger.Log($"Payload type [{typeof(P).Name}] has no callbacks to remove!", LogCategory.PayloadCallbacks, LogLevel.Warning);
                    }
                }
                else
                {
                    NetworkLogger.Log("Cannot remove callbacks for types with no NetworkTag!", LogCategory.PayloadCallbacks, LogLevel.Warning);
                }
            }
        }
Exemple #3
0
        protected override void OnConnect(Event e)
        {
            Peer peer = e.Peer;
            uint id   = peer.ID + 1;           // Increase by 1 so ID of 0 remains free for host

            if (peer.IsSet)
            {
                NetworkLogger.Log($"Client [{id}] connected", LogCategory.Connections);

                var client = new FlareClientShell(peer)
                {
                    Id = id
                };
                ClientManager?.AddClient(client);

                // Send the client its ID manually
                PayloadHandler.AddCallback <ClientAssigned>(PushClientConnected);
                SendMessage(new IdAssignment {
                    id = id
                }, 0, peers: client.Peer);
            }
            else
            {
                NetworkLogger.Log("Unset peer connected. How?", LogCategory.Connections, LogLevel.Error);
            }
        }
Exemple #4
0
            internal void Add <T>(FlarePayloadCallback <T> callback) where T : INetworkPayload
            {
                int key = callback.GetHashCode();

                if (!Values.ContainsKey(key))
                {
                    // This cast needs benchmarking
                    Values.Add(key, x =>
                    {
                        if (x is T p)
                        {
                            callback(p);
                        }
                    });

                    if (Type.IsVisible)
                    {
                        NetworkLogger.Log($"Added delegate [{callback.Method.Name}] for payload type [{Name}]", LogCategory.PayloadCallbacks);
                    }
                }
                else
                {
                    NetworkLogger.Log($"Delegate [{callback.Method.Name}] is already added to listen for payload type [{Name}]", LogCategory.PayloadCallbacks, LogLevel.Warning);
                }
            }
Exemple #5
0
        /// <summary>
        /// Add a callback to listen for payloads of a given type.
        /// </summary>
        /// <typeparam name="T">The payload type to listen for</typeparam>
        /// <param name="callback">The delegate to call</param>
        public void AddCallback <T>(FlarePayloadCallback <T> callback) where T : INetworkPayload
        {
            if (isInvoking)
            {
                registrationQueue.Enqueue(() => Add(callback));
            }
            else
            {
                Add(callback);
            }

            void Add <P>(FlarePayloadCallback <P> c) where P : INetworkPayload
            {
                var type = typeof(P);
                var tag  = NetworkTagAttribute.GetTag(type);

                if (tag != null)
                {
                    // Add the callback to the dictionary
                    if (!payloadCallbacks.TryGetValue(tag.Value, out var value))
                    {
                        // Create callback entry if it doesn't exist
                        value = new Callback(type);
                        payloadCallbacks.Add(tag.Value, value);
                    }

                    value.Add(c);
                }
                else
                {
                    NetworkLogger.Log("Cannot add callbacks for types with no NetworkTag!", LogCategory.PayloadCallbacks, LogLevel.Message);
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Remove all registered callbacks for a given payload type.
        /// </summary>
        /// <typeparam name="T">The type to remove callbacks for</typeparam>
        public void ClearCallbacks <T>() where T : INetworkPayload
        {
            if (isInvoking)
            {
                registrationQueue.Enqueue(() => Clear <T>());
            }
            else
            {
                Clear <T>();
            }

            void Clear <P>() where P : INetworkPayload
            {
                var tag = NetworkTagAttribute.GetTag(typeof(P));

                if (tag != null)
                {
                    if (payloadCallbacks.ContainsKey(tag.Value))
                    {
                        payloadCallbacks.Remove(tag.Value);
                        NetworkLogger.Log($"Cleared callbacks for payload type [{typeof(P).Name}]", LogCategory.PayloadCallbacks);
                    }
                    else
                    {
                        NetworkLogger.Log($"Payload type [{typeof(P).Name}] has no callbacks to clear!", LogCategory.PayloadCallbacks, LogLevel.Warning);
                    }
                }
                else
                {
                    NetworkLogger.Log("Cannot clear callbacks for types with no NetworkTag!", LogCategory.PayloadCallbacks, LogLevel.Warning);
                }
            }
        }
Exemple #7
0
    public byte[] GetPacketData()
    {
        int size = ReadPacketSize();

        if (size <= 0)
        {
            return(null);
        }

        byte[] data = new byte[size];

        try {
            memoryStream.Position = sizeof(int);
            memoryStream.Read(data, 0, size);

            byte[] stream     = memoryStream.ToArray();
            int    restSize   = stream.Length - size - sizeof(int);
            byte[] restStream = new byte[restSize];
            Buffer.BlockCopy(stream, size + sizeof(int), restStream, 0, restSize);

            memoryStream = new MemoryStream(restStream);
            offset       = restSize;
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
            return(null);
        }
        return(data);
    }
Exemple #8
0
    /*
     * +-------------------------+
     * |        Connection       |
     * +-------------------------+
     */

    public bool Connect(string address, int port)
    {
        if (socket != null)
        {
            return(false);
        }

        try {
            socket         = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.NoDelay = true;
            socket.Connect(address, port);

            isConnected = true;
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
            socket      = null;
            isConnected = false;
        }

        sendQueue.Clear();
        recvQueue.Clear();

        if (networkStateHandler != null)
        {
            NetworkState state = new NetworkState();
            state.type   = NetEventType.Connect;
            state.result = isConnected == true ? NetEventResult.Success : NetEventResult.Failure;
            networkStateHandler(this, state);
        }

        return(isConnected);
    }
Exemple #9
0
    public override void AcceptClient()
    {
        if ((this.listener != null) && this.listener.Poll(0, SelectMode.SelectRead))
        {
            Socket socket = this.listener.Accept();

            int node = -1;
            try {
                TransportTCP transport = new TransportTCP();
                transport.Initialize(socket);
                transport.transportName = "serverSocket";
                node = JoinSession(transport);
            } catch (Exception e) {
                NetworkLogger.Log(e.ToString());
                return;
            }

            if (node >= 0 && this.networkStateHandler != null)
            {
                NetworkState state = new NetworkState();
                state.type   = NetEventType.Connect;
                state.result = NetEventResult.Success;
                this.networkStateHandler(node, state);
            }
        }
    }
Exemple #10
0
 protected virtual void OnTimeout(Event e)
 {
     NetworkLogger.Log(NetworkLogEvent.ClientTimeout);
     PayloadHandler.PushPayload(new ClientDisconnected {
         ClientId = Id
     });
 }
Exemple #11
0
    /*
     * +-------------------------+
     * |       Constructor       |
     * +-------------------------+
     */

    public Session()
    {
        try {
            this.transports = new Dictionary <int, T>();
            this.mtu        = DEFAULT_MTU_SIZE;
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
        }
    }
Exemple #12
0
            internal void Invoke(INetworkPayload value)
            {
                NetworkLogger.Log($"Invoking payload type [{Name}]", LogCategory.PayloadProcessing);

                foreach (var v in Values.Values)
                {
                    v.Invoke(value);
                }
            }
 /// <summary>
 /// Remove a client from the client manager by ID.
 /// </summary>
 /// <param name="id">The ID of the client to remove</param>
 internal void RemoveClient(uint id)
 {
     if (TryGetClient(id, out var client))
     {
         connectedClients.Remove(id);
     }
     else
     {
         NetworkLogger.Log($"Unable to remove nonexistent peer with ID [{id}] from ClientManager!", LogCategory.Connections, LogLevel.Error);
     }
 }
Exemple #14
0
        private void PushClientConnected(ClientAssigned p)
        {
            NetworkLogger.Log("Client connection finalized", LogCategory.Connections);
            PayloadHandler.RemoveCallback <ClientAssigned>(PushClientConnected);

            if (ClientManager.TryGetClient(p.id, out var client))
            {
                PayloadHandler.PushPayload(new ClientConnected {
                    Client = client
                });
            }
        }
Exemple #15
0
    public override bool CreateListener(int port, int connectionMax)
    {
        try {
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            listener.Bind(new IPEndPoint(IPAddress.Any, port));
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
            return(false);
        }

        return(true);
    }
Exemple #16
0
        private void AssignID(IdAssignment p)
        {
            // Don't listen for the ID anymore
            RemoveCallback <IdAssignment>(AssignID);

            Id = p.id;

            NetworkLogger.Log($"Client initialized with ID [{Id}]", LogCategory.Connections);
            SendMessage(new ClientAssigned {
                id = Id
            });
        }
Exemple #17
0
 public override void OnConnectedToMaster()
 {
     NetworkLogger.Log("Connected to Master");
     Debug.Log("PUN Basics Tutorial/Launcher: OnConnectedToMaster() was called by PUN");
     if (connectToRandomRoom)
     {
         PhotonNetwork.JoinRandomRoom();
     }
     else
     {
         PhotonNetwork.JoinRoom(roomID);
     }
 }
Exemple #18
0
    protected bool WriteRawBuffer(byte[] data, int size)
    {
        try {
            buffer.Position = offset;
            buffer.Write(data, 0, size);
            offset += size;
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
            return(false);
        }

        return(true);
    }
Exemple #19
0
        private void StartServer(ushort port)
        {
            // Create the address and host
            Address = new Address {
                Port = port
            };
            Host.Create(Address, Config.MaxConnections, Config.ChannelCount);

            ClientManager = new FlareClientManager(Config.MaxConnections);
            StartUpdateThread();

            NetworkLogger.Log(NetworkLogEvent.ServerStart);
        }
Exemple #20
0
    /*
     * +-------------------------+
     * |          Thread         |
     * +-------------------------+
     */

    protected bool CreateThread()
    {
        try {
            this.thread     = new Thread(new ThreadStart(ThreadDispatch));
            this.threadLoop = true;
            this.thread.Start();
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
            return(false);
        }

        return(true);
    }
Exemple #21
0
    public bool SetDeserializedData(byte[] data)
    {
        Clear();

        try {
            buffer.Write(data, 0, data.Length);
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
            return(false);
        }

        return(true);
    }
Exemple #22
0
 public bool AddBuffer(byte[] data, int size)
 {
     try {
         memoryStream.Position = offset;
         memoryStream.Write(data, 0, size);
         offset += size;
     } catch (Exception e) {
         NetworkLogger.Log(e.ToString());
         memoryStream.Flush();
         offset = 0;
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// Add a client to the client manager.
        /// </summary>
        /// <param name="client"></param>
        internal void AddClient(FlareClientShell client)
        {
            uint id = client.Id;

            // Add client to the connect clients dictionary
            if (!connectedClients.ContainsKey(id))
            {
                connectedClients.Add(id, client);
            }
            else
            {
                NetworkLogger.Log($"Unable to add already existing peer with ID [{id}] to ClientManager!", LogCategory.Connections, LogLevel.Error);
            }
        }
Exemple #24
0
 /// <summary>
 /// Turn a message into a payload if a listener for it exists.
 /// </summary>
 /// <param name="message">The message to process</param>
 public void ProcessMessage(Message message)
 {
     if (payloadCallbacks.TryGetValue(message.Tag, out var callback) && callback.Count > 0)
     {
         var value = (INetworkPayload)Activator.CreateInstance(callback.Type);
         message.Process(ref value);
         pollQueue.Enqueue(new MessagePayload {
             Value = value, Callback = callback
         });
     }
     else
     {
         NetworkLogger.Log($"There are no listeners for NetworkTag [{message.Tag}]!", LogCategory.PayloadProcessing, LogLevel.Warning);
     }
 }
Exemple #25
0
        public override void OnJoinedRoom()
        {
            if (PhotonNetwork.CurrentRoom.PlayerCount == maxPlayersPerRoom)
            {
                OnRoomFullCallback?.Invoke();
                Debug.Log("Room full!");
            }
            else
            {
                NetworkLogger.Log($"Room ID : {PhotonNetwork.CurrentRoom.Name}");
                Debug.Log("PUN Basics Tutorial/Launcher: OnJoinedRoom() called by PUN. Now this client is in a room.");
            }

            OnRoomJoinedCallback?.Invoke();
        }
Exemple #26
0
        public virtual void SendMessage <T>(T value, byte channel = 0) where T : INetworkPayload
        {
            var tag = NetworkTagAttribute.GetTag(typeof(T));

            if (tag != null)
            {
                using (Message m = new Message(tag.Value))
                {
                    m.Process(ref value);
                    SendMessage(m, tag.PacketFlags, channel);
                }
            }
            else
            {
                NetworkLogger.Log("Cannot send a NetworkPayload with no NetworkTag!", LogCategory.PayloadProcessing);
            }
        }
Exemple #27
0
        public override void SendMessage <T>(T value, byte channel = 0, params IClient[] clients)
        {
            var tag = NetworkTagAttribute.GetTag(typeof(T));

            if (tag != null)
            {
                using (Message m = new Message(tag.Value))
                {
                    m.Process(ref value);
                    SendMessage(m, tag.PacketFlags, channel, clients);
                }
            }
            else
            {
                NetworkLogger.Log("Cannot send a NetworkPayload with no NetworkTag!", LogCategory.PayloadProcessing, LogLevel.Warning);
            }
        }
Exemple #28
0
        private void SendMessage <T>(T value, byte channel, params Peer[] peers) where T : INetworkPayload
        {
            var tag = NetworkTagAttribute.GetTag(typeof(T));

            if (tag != null)
            {
                using (Message m = new Message(tag.Value))
                {
                    m.Process(ref value);
                    SendMessage(m, tag.PacketFlags, channel, peers);
                }
            }
            else
            {
                NetworkLogger.Log("Cannot send a NetworkPayload with no NetworkTag!", LogCategory.PayloadProcessing, LogLevel.Warning);
            }
        }
Exemple #29
0
        /// <summary>
        /// Disconnects all clients and shuts the server down.
        /// </summary>
        public override void Disconnect()
        {
            NetworkLogger.Log(NetworkLogEvent.ServerStop);

            // Kick all remaining clients off
            var clients = ClientManager.GetAllClients();

            foreach (FlareClientShell client in clients)
            {
                client.Disconnect();
            }

            ClientManager = null;

            // Shut the rest of the client down
            Shutdown();
        }
Exemple #30
0
    protected bool WriteBuffer(byte[] data, int size)
    {
        if (endianType == EndianType.LittleEndian)
        {
            Array.Reverse(data);
        }

        try {
            buffer.Position = offset;
            buffer.Write(data, 0, size);
            offset += size;
        } catch (Exception e) {
            NetworkLogger.Log(e.ToString());
            return(false);
        }

        return(true);
    }