Exemplo n.º 1
0
        /// <summary>
        /// Connects to a server
        /// </summary>
        public bool Connect(IPAddress address, int port, byte[] customData)
        {
            if (m_serverConnection != null && m_serverConnection.Status != NetConnectionStatus.Disconnected)
            {
                m_serverConnection.Disconnect("Reconnecting");
            }

            IPEndPoint remoteIP = new IPEndPoint(address, port);

            m_serverConnection = new NetConnection(this, remoteIP);

            string remoteHost = remoteIP.ToString();

            Log.Info("Connecting to " + remoteHost);

            m_serverConnection.m_firstSentHandshake = NetTime.Now;
            m_serverConnection.m_lastSentHandshake  = m_serverConnection.m_firstSentHandshake;
            m_serverConnection.SetStatus(NetConnectionStatus.Connecting, "Connecting");

            // save custom data for repeat connect requests
            if (customData != null)
            {
                m_serverConnection.m_savedConnectCustomData = new byte[customData.Length];
                Array.Copy(customData, m_serverConnection.m_savedConnectCustomData, customData.Length);
            }

            int bytesSent = NetHandshake.SendConnect(this, remoteIP, customData);

            // account for connect packet
            m_serverConnection.Statistics.PacketsSent++;
            m_serverConnection.Statistics.MessagesSent++;
            m_serverConnection.Statistics.BytesSent += bytesSent;

            return(true);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Disconnects from remote host providing specified reason
        /// </summary>
        public void Disconnect(string reason)
        {
            if (m_status != NetConnectionStatus.Disconnected)
            {
                SendUnsentMessages(true, 1.0f);                 // flush

                NetHandshake.SendDisconnected(m_parent, reason, this);
                if (m_unsentMessages.Count < 1)
                {
                    SetStatus(NetConnectionStatus.Disconnected, reason);
                }
                else
                {
                    SetStatus(NetConnectionStatus.Disconnecting, reason);
                    m_pendingDisconnectedReason = reason;
                }
            }
        }
Exemplo n.º 3
0
        internal override void HandlePacket(NetBuffer buffer, int bytesReceived, IPEndPoint senderEndpoint)
        {
            double        now    = NetTime.Now;
            NetConnection sender = FindConnection(senderEndpoint);

            if (sender != null)
            {
                sender.m_lastHeardFromRemote = now;

                if (sender.m_encryption.SymmetricEncryptionKeyBytes != null)
                {
                    bool ok = sender.m_encryption.DecryptSymmetric(buffer);
                    if (!ok)
                    {
                        Log.Warning("Failed to decrypt packet from client " + sender);
                        return;
                    }
                }
            }

            try
            {
                NetMessage response;
                int        messagesReceived    = 0;
                int        usrMessagesReceived = 0;
                int        ackMessagesReceived = 0;
                while (buffer.ReadBitsLeft > 7)
                {
                    NetMessage msg = NetMessage.Decode(buffer);
                    if (msg == null)
                    {
                        break;                         // done
                    }
                    messagesReceived++;
                    msg.Sender = sender;
                    switch (msg.m_type)
                    {
                    case NetMessageType.Acknowledge:
                    case NetMessageType.AcknowledgeBitField:
                        if (sender == null)
                        {
                            Log.Warning("Received Ack from not-connected source!");
                        }
                        else
                        {
                            //Log.Debug("Received ack " + msg.SequenceChannel + "|" + msg.SequenceNumber);
                            sender.ReceiveAcknowledge(msg);
                            ackMessagesReceived++;
                        }
                        break;

                    case NetMessageType.Handshake:
                        NetHandshakeType tp = (NetHandshakeType)msg.ReadByte();
                        if (tp == NetHandshakeType.ConnectResponse)
                        {
                            Log.Warning("Received ConnectResponse?!");
                        }
                        else if (tp == NetHandshakeType.Connect)
                        {
                            if (sender == null)
                            {
                                NetHandshake.HandleConnect(msg, this, senderEndpoint);
                            }
                            else
                            {
                                // resend response
                                NetHandshake.SendConnectResponse(this, sender, senderEndpoint);
                                Log.Verbose("Redundant Connect received; resending response");
                            }
                        }
                        else if (tp == NetHandshakeType.ConnectionEstablished)
                        {
                            if (sender == null)
                            {
                                Log.Warning("Received ConnectionEstablished, but no sender connection?!");
                            }
                            else
                            {
                                float rt = (float)(now - sender.m_firstSentHandshake);
                                sender.m_ping.Initialize(rt);

                                ushort remoteValue = msg.ReadUInt16();
                                sender.RemoteClockOffset = NetTime.CalculateOffset(now, remoteValue, rt);
                                Log.Verbose("Reinitializing remote clock offset to " + sender.RemoteClockOffset + " ms (roundtrip " + NetUtil.SecToMil(rt) + " ms)");

                                if (sender.Status == NetConnectionStatus.Connected)
                                {
                                    Log.Verbose("Redundant ConnectionEstablished received");
                                }
                                else
                                {
                                    Log.Debug("Connection established");
                                    sender.SetStatus(NetConnectionStatus.Connected, "Connected by established");
                                }
                            }
                        }
                        else
                        {
                            // disconnected
                            if (sender == null)
                            {
                                Log.Warning("Disconnected received from unconnected source: " + senderEndpoint);
                                return;
                            }
                            string reason = msg.ReadString();
                            sender.Disconnected(reason);
                        }
                        break;

                    case NetMessageType.Discovery:
                        Log.Debug("Answering discovery response from " + senderEndpoint);
                        response = NetDiscovery.EncodeResponse(this);
                        SendSingleMessageAtOnce(response, null, senderEndpoint);
                        break;

                    case NetMessageType.PingPong:

                        if (sender == null)
                        {
                            return;
                        }

                        bool isPong         = msg.ReadBoolean();
                        bool isOptimizeInfo = msg.ReadBoolean();
                        if (isOptimizeInfo)
                        {
                            // DON'T handle optimizeinfo... only clients should adapt to server ping info
                        }
                        else if (isPong)
                        {
                            if (sender.Status == NetConnectionStatus.Connected)
                            {
                                sender.m_ping.HandlePong(now, msg);
                            }
                        }
                        else
                        {
                            NetPing.ReplyPong(msg, sender);                                     // send pong
                        }
                        break;

                    case NetMessageType.User:
                    case NetMessageType.UserFragmented:
                        usrMessagesReceived++;
                        if (sender == null)
                        {
                            Log.Warning("User message received from unconnected source: " + senderEndpoint);
                            return;                                     // don't handle user messages from unconnected sources
                        }
                        if (sender.Status == NetConnectionStatus.Connecting)
                        {
                            sender.SetStatus(NetConnectionStatus.Connected, "Connected by user message");
                        }
                        sender.ReceiveMessage(now, msg);
                        break;

                    default:
                        Log.Warning("Bad message type: " + msg);
                        break;
                    }
                }

                if (sender != null)
                {
                    NetStatistics stats = sender.Statistics;
                    stats.PacketsReceived++;
                    stats.MessagesReceived     += messagesReceived;
                    stats.UserMessagesReceived += usrMessagesReceived;
                    stats.AckMessagesReceived  += ackMessagesReceived;
                    stats.BytesReceived        += bytesReceived;
                }
            }
            catch (Exception ex)
            {
                Log.Error("Failed to parse packet correctly; read/write mismatch? " + ex);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Connection heartbeat, normally called from NetClient.Heartbeat() or NetServer.Heartbeat()
        /// Calling it manually may interfere with proper throttling
        /// </summary>
        public void Heartbeat(double now)
        {
            m_frameLength   = now - m_lastHeartbeat;
            m_lastHeartbeat = now;

            // resend timed out saved packets
            for (int i = 0; i < m_savedReliableMessages.Length; i++)
            {
                if (m_savedReliableMessages[i] != null && m_savedReliableMessages[i].Count > 0)
                {
                    foreach (NetMessage msg in m_savedReliableMessages[i])
                    {
                        if (now > msg.m_nextResendTime)
                        {
                            // it might have been lost; resend it
                            if (msg.m_numResends >= Configuration.NumResendsBeforeFailing)
                            {
                                m_parent.Log.Error("Dropping outgoing packet " + msg + "; maximum number of resends reached!");
                            }
                            else
                            {
                                if (MessageResent != null)
                                {
                                    MessageResent(this, new NetMessageEventArgs(msg));
                                }
                                //m_parent.Log.Verbose("Resending " + msg + " @ " + now);
                                m_unsentMessages.Enqueue(msg);

                                float nextResend = (float)now + (msg.m_numResends < 1 ? Configuration.ResendFirstUnacknowledgedDelay : Configuration.ResendSubsequentUnacknowledgedDelay);
                                msg.m_nextResendTime = nextResend;

                                msg.m_numResends++;
                                Statistics.MessagesResent++;
                            }
                            m_tmpRemoveList.Add(msg);                             // to be removed
                        }
                    }

                    if (m_tmpRemoveList.Count > 0)
                    {
                        foreach (NetMessage rm in m_tmpRemoveList)
                        {
                            m_savedReliableMessages[i].Remove(rm);                             // remove it; it will be readded upon sending
                        }
                        m_tmpRemoveList.Clear();
                    }
                }
            }

            // send all messages (possibly forcing acks to be sent)
            SendUnsentMessages((m_forceExplicitAckTime != 0.0 && now > m_forceExplicitAckTime),
                               (m_frameLength > 0.1 ? 0.1 : m_frameLength));  // throttling don't like unlikely long frames

            if (now - m_lastHeardFromRemote > Configuration.ConnectionTimeOut)
            {
                NetHandshake.SendDisconnected(m_parent, "Connection timed out", this);
                SetStatus(NetConnectionStatus.Disconnected, "Connection timed out");
                return;
            }

            if (m_status == NetConnectionStatus.Connecting)
            {
                // keep sending connect packets
                if (now - m_lastSentHandshake > NetConstants.SendHandshakeFrequency)
                {
                    if (now - m_firstSentHandshake > NetConstants.ConnectAttemptTimeout)
                    {
                        m_parent.Log.Info("Failed to connect; no answer from remote host!");
                        SetStatus(NetConnectionStatus.Disconnected, "Connect attempt timeout");
                    }
                    else
                    {
                        NetClient client = m_parent as NetClient;
                        if (client != null)
                        {
                            int bytesSent = NetHandshake.SendConnect(client, m_remoteEndpoint, m_savedConnectCustomData);
                            client.ServerConnection.Statistics.PacketsSent++;
                            client.ServerConnection.Statistics.MessagesSent++;
                            client.ServerConnection.Statistics.BytesSent += bytesSent;
                            m_lastSentHandshake = now;
                        }
                        else
                        {
                            NetHandshake.SendConnectResponse(m_parent, this, m_remoteEndpoint);
                            m_lastSentHandshake = now;
                        }
                    }
                }
                return;
            }

            m_ping.Heartbeat(now);
        }