Example #1
0
    private static void RecieveCallbackUDP(IAsyncResult AR)
    {
        ClientSocket clientSocket = (ClientSocket)AR.AsyncState;

        try
        {
            // Problem part! this is what locks it up when play/stop/play
            byte[] packetData = clientSocket.udpClient.EndReceive(AR, ref clientSocket.udpEndPointRemote);

            // continue recieving packets
            clientSocket.udpClient.BeginReceive(new AsyncCallback(RecieveCallbackUDP), clientSocket);

            FFBasePacket packet;
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                FFSystem.InitBinaryFormatter(bf);
                MemoryStream ms = new MemoryStream((byte[])packetData);
                packet = (FFBasePacket)bf.Deserialize(ms);
                ms.Dispose();
            }
            catch (Exception exp)
            {
                Debug.Log("FFPacket not deserializable (Client UDP)" +
                          "\nException: " + exp.Message +
                          "\nPacket Sise: " + packetData.Length);
                return;
            }

            FFSystem.DisbatchPacket(packet);
            //Debug.Log("Recieve CallbackUDP (Client)"); // debug
        }
        catch (Exception exp)
        {
            Debug.LogError("Error in RecieveCallbackUDP (Client)" +
                           "\nException: " + exp.Message +
                           "\nClient ID: " + clientSocket.clientData.clientId +
                           "\nClient Name: " + clientSocket.clientData.clientName +
                           "\nUDPEndpointLocal: " + clientSocket.udpEndPointLocal +
                           "\nUDPEndPointRemote: " + clientSocket.udpEndPointRemote);
        }
    }
Example #2
0
    private static void ProcessRecievedPacket(ClientSocket clientSocket, byte[] packetData)
    {
        MemoryStream    msSendBuffer = new MemoryStream(packetData);
        BinaryFormatter bf           = new BinaryFormatter();

        FFSystem.InitBinaryFormatter(bf);

        FFBasePacket packet;

        try
        {
            packet = (FFBasePacket)bf.Deserialize(msSendBuffer); // if packed cannot
            msSendBuffer.Dispose();
        }
        catch (Exception exp)
        {
            Debug.Log("FFPacket not deserializable (Server)" +
                      "\nException: " + exp.Message +
                      "\nPacket Sise: " + packetData.Length);
            return;
        }

        #region MessageInspectors
        List <BaseMessageInspector> inspectors;
        uint sendToOtherClients = 0; // if any inspectors return a non-zero number, don't distribute to others

        if (singleton._messageInspectors.TryGetValue(packet.messageType, out inspectors))
        {
            foreach (var insp in inspectors)
            {
                try
                {
                    sendToOtherClients |= insp.Inspect(clientSocket, packet);
                }
                catch (Exception exp)
                {
                    Debug.LogError("Error in messageInspector: " + insp.ToString() +
                                   "\nException: " + exp.Message);
                }
            }
        }
        #endregion

        #region RelayMessages
        try
        {
            // if none of the inspectors return a non-zero number the message will be relayed to all other clients
            if (sendToOtherClients == 0)
            {
                // inspectors can modify packects to be send to all other clients, need to re-serialize this
                MemoryStream msBroadcast = new MemoryStream();
                bf.Serialize(msBroadcast, packet);
                byte[] broadcastPacketData = msBroadcast.ToArray();
                msBroadcast.Flush();
                msBroadcast.Dispose();

                // Other Clients
                if (clientSocket.udpClient == null) //TCP
                {
                    // Send out packet to others
                    foreach (var cDataEntry in singleton._clientDataList)
                    {
                        ClientSocket sendToClientSocket = cDataEntry.clientSocketTCP;
                        if (clientSocket.Equals(sendToClientSocket) == false)
                        {
                            sendToClientSocket.socket.BeginSend(broadcastPacketData, 0, broadcastPacketData.Length, SocketFlags.None,
                                                                new AsyncCallback(SendCallbackTCP), sendToClientSocket);
                        }
                    }
                }
                else if (clientSocket.udpClient != null) //UDP
                {
                    ClientData cData;
                    if (singleton._clientData.TryGetValue(packet.senderId, out cData))
                    {
                        // Send out packet to others
                        foreach (var cDataEntry in singleton._clientDataList)
                        {
                            if (cData.clientId != cDataEntry.clientId)
                            {
                                /*Debug.Log("Sending Data to: " + cDataEntry.clientSocketUDP.udpEndPointRemote +
                                 *  "\nClient Id: " + cDataEntry.clientId +
                                 *  "\nPacket.instructions: " + packet.packetInstructions +
                                 *  "\nPacket.entry: " + packet.entry +
                                 *  "\nPacket.messageType: " + packet.messageType +
                                 *  "\nPacket.senderId: " + packet.senderId);*/
                                // debug

                                //Debug.Log("Send UDP packet to " + sendToClientSocket.udpEndPointRemote);
                                cDataEntry.clientSocketUDP.udpClient.Send(broadcastPacketData, broadcastPacketData.Length, cDataEntry.clientSocketUDP.udpEndPointRemote);
                            }

                            /*else // debug
                             * {
                             *  Debug.Log("NOT SENDING TO: " + cDataEntry.clientSocketUDP.udpEndPointRemote +
                             *      "\nClient Id: " + cDataEntry.clientId +
                             *      "\nPacket.instructions: " + packet.packetInstructions +
                             *      "\nPacket.entry: " + packet.entry +
                             *      "\nPacket.messageType: " + packet.messageType +
                             *      "\nPacket.senderId: " + packet.senderId); //debug
                             * }*/
                            //debug
                        }
                    }
                    else
                    {
                        Debug.LogError("Error in ProcessingRecievedPackets" +
                                       "\nCould not find the ClientData connected to the senderId." +
                                       "\nPacket could not be relayed");
                    }
                }
                else // Socket Data is screwed up...
                {
                    Debug.LogError("Error in ProcessingRecievedPackets" +
                                   "\nClientData connected to ClientSocket is messed up...?");
                }

                // Send to Local, because this Unity instance doesn't have a local client to listen through packet.
                // This will be done if we are a dedicated server
                if (singleton._sendToLocal)
                {
                    FFSystem.DisbatchPacket(packet);
                }
            }
        }
        catch (Exception exp)
        {
            Debug.LogError("Exception Error in ProcessingRecievedPackets" +
                           "\nException: " + exp.Message +
                           "\nPacketData.Instructions: " + packet.packetInstructions +
                           "\nPacketData.entry: " + packet.entry +
                           "\nPacketData.MessageType: " + packet.messageType);
        }
        #endregion
    }
Example #3
0
        public void SendNetPacket <MessageType>(FFPacket <MessageType> packet, bool varifiedPacket)
        {
            long senderId = packet.senderId; // Client Id

            packet.senderId = 0;             // from Server, id: 0

            MemoryStream    ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();

            FFSystem.InitBinaryFormatter(bf);
            FFPacket <MessageType> .Encrypt(ref packet.message);

            /*------------------------------*/
            // Get client Data
            ClientData cData;

            // Valid Client Ids: 1 - MaxLong
            if (singleton._clientData.TryGetValue(senderId, out cData))
            {
            }
            else if (senderId == -1) // -1 is for UnInitialized IDs
            {
                // Un Initialized ID will not be able to send UDP Packets to the correct client, but TCP should work.
                cData = clientData;
                Debug.Log("Recieved Uninitialized SenderId"); // debug
            }
            else // Bad ID
            {
                Debug.LogError("Error in FFServer.ClientSocket.SendNetPacket<" + typeof(MessageType).ToString() + ">(FFPacket<" + typeof(MessageType).ToString() + ">, bool " +
                               "\nTried to Send a packet, but we couldn't find the senderId's ClientData." +
                               "\nSenderId: " + senderId);
                return;
            }
            /*------------------------------*/

            bf.Serialize(ms, packet);
            byte[] packetData = ms.GetBuffer();
            ms.Flush();
            ms.Dispose();

            try
            {
                if (varifiedPacket == true)
                {
                    //Debug.Log("Server Sent Packet via TCP of type :" + typeof(MessageType).ToString()); // debug
                    cData.clientSocketTCP.socket.BeginSend(packetData, 0, packetData.Length, SocketFlags.None, new AsyncCallback(SendCallbackTCP), cData.clientSocketTCP);
                }
                else
                {
                    //Debug.Log("Server Sent Packet via UDP of type :" + typeof(MessageType).ToString()); // debug
                    cData.clientSocketUDP.udpClient.Send(packetData, packetData.Length, cData.clientSocketUDP.udpEndPointRemote);
                }
            }
            catch (Exception exp)
            {
                Debug.LogError("Error in FFServer.ClientSocket.SendNetPacket<" + typeof(MessageType).ToString() + ">(FFPacket<" + typeof(MessageType).ToString() + ">, bool)" +
                               "\nException: " + exp.Message +
                               "\nClient ID: " + clientData.clientId +
                               "\nClient Name: " + clientData.clientName);
                return;
            }
        }
Example #4
0
    private static void RecieveCallbackTCP(IAsyncResult AR)
    {
        SocketError  socketError  = SocketError.Success;
        ClientSocket clientSocket = (ClientSocket)AR.AsyncState;

        try
        {
            int recieved = clientSocket.socket.EndReceive(AR, out socketError);
            if (recieved != 0 && socketError == SocketError.Success)
            {
                byte[] packetData = new byte[recieved];
                Array.Copy(clientSocket.recieveDataBuffer, packetData, recieved);

                // continue recieving packets
                clientSocket.socket.BeginReceive(clientSocket.recieveDataBuffer, 0, clientSocket.recieveDataBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallbackTCP), clientSocket);

                FFBasePacket packet;
                try
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    FFSystem.InitBinaryFormatter(bf);
                    MemoryStream ms = new MemoryStream(packetData);
                    packet = (FFBasePacket)bf.Deserialize(ms);
                    ms.Dispose();
                }
                catch (Exception exp)
                {
                    Debug.Log("FFPacket not deserializable (Client TCP)" +
                              "\nException: " + exp.Message +
                              "\nPacket Sise: " + packetData.Length);
                    return;
                }

                FFSystem.DisbatchPacket(packet);
                //Debug.Log("Recieve CallbackTCP (Client)"); //debug
            }
            else
            {
                if (socketError != SocketError.Success)
                {
                    Debug.LogError("RecieveCallbackTCP SocketShutdown (Client)" +
                                   "\nSocketError: " + socketError +
                                   "\nClient ID: " + clientSocket.clientData.clientId +
                                   "\nClient Name: " + clientSocket.clientData.clientName);
                }
                else
                {
                    Debug.Log("RecieveCallbackTCP SocketShutdown (Client)" +
                              "\nClient ID: " + clientSocket.clientData.clientId +
                              "\nClient Name: " + clientSocket.clientData.clientName);
                }
            }
        }
        catch (Exception exp)
        {
            if (socketError != SocketError.Success)
            {
                Debug.LogError("Error in RecieveCallbackTCP (Client)" +
                               "\nException: " + exp.Message +
                               "\nSocketError: " + socketError +
                               "\nClient ID: " + clientSocket.clientData.clientId +
                               "\nClient Name: " + clientSocket.clientData.clientName);
            }
            else
            {
                Debug.LogError("Error in RecieveCallbackTCP (Client)" +
                               "\nException: " + exp.Message +
                               "\nClient ID: " + clientSocket.clientData.clientId +
                               "\nClient Name: " + clientSocket.clientData.clientName);
            }
        }
    }
Example #5
0
    private static void SendThreadLoop()
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream    ms = new MemoryStream();

        FFSystem.InitBinaryFormatter(bf);

        uint PingCycle          = (uint)(singleton._PingCycle * 1000.0f);
        uint DialationSyncCycle = (uint)(singleton._DialationSyncCycle * 1000.0f);
        // Sync Counters (in milliseconds)
        uint DialationSyncTimeCounter = DialationSyncCycle;
        uint PingTimeCounter          = 0;

        System.Diagnostics.Stopwatch sendThreadWatch = new System.Diagnostics.Stopwatch();
        sendThreadWatch.Start();

        while (true)
        {
            int cyclePacketCount = 0;

            // sync Client if needed
            if (FFClient.isReady)
            {
                if (sendThreadWatch.ElapsedMilliseconds >= PingTimeCounter)
                {
                    PingTimeCounter += PingCycle;
                    SendClientSyncTimeEvent(false);
                    //Debug.Log("SendThread sent a ClientSyncTimeEvent w/o Dialation"); //debug
                }

                if (sendThreadWatch.ElapsedMilliseconds >= DialationSyncTimeCounter)
                {
                    DialationSyncTimeCounter += DialationSyncCycle;
                    SendClientSyncTimeEvent(true);
                    //Debug.Log("SendThread sent a ClientSyncTimeEvent w/ Dialation"); //debug
                }
            }

            while (singleton._packetsToSendViaTCP.Count != 0)
            {
                ms = new MemoryStream();
                FFBasePacket packet = singleton._packetsToSendViaTCP.Dequeue();
                bf.Serialize(ms, packet);

                byte[] packetData = ms.GetBuffer();
                ms.Flush();
                ms.Dispose();

                SendPacketTCP(packetData);
                ++cyclePacketCount;
                //Debug.Log("SendThead Sent a TCP packet"); // debug
            }

            while (singleton._packetsToSendViaUDP.Count != 0)
            {
                ms = new MemoryStream();
                FFBasePacket packet = singleton._packetsToSendViaUDP.Dequeue();
                bf.Serialize(ms, packet);

                byte[] packetData = ms.GetBuffer();
                ms.Flush();
                ms.Dispose();

                SendPacketUDP(packetData);
                ++cyclePacketCount;
                //Debug.Log("SendThead Sent a UDP packet"); // debug
            }


            if (cyclePacketCount == 0) // if we didn't send anything
            {
                Thread.Sleep(1);       // Throw on CPU thead queue
            }
        }
    }