Procházet zdrojové kódy

external server used for automatic guid detection, http calls are made trough networking library

Arnis Lielturkss před 7 roky
rodič
revize
56bb3b31a8

+ 33 - 5
Source/Samples/54_P2PMultiplayer/P2PMultiplayer.cpp

@@ -35,6 +35,7 @@
 #include <Urho3D/IO/VectorBuffer.h>
 #include <Urho3D/Network/Network.h>
 #include <Urho3D/Network/NetworkEvents.h>
+#include <Urho3D/Network/HttpRequest.h>
 #include <Urho3D/Physics/CollisionShape.h>
 #include <Urho3D/Physics/PhysicsEvents.h>
 #include <Urho3D/Physics/PhysicsWorld.h>
@@ -148,6 +149,7 @@ void P2PMultiplayer::SubscribeToEvents()
 
     SubscribeToEvent(E_CLIENTCONNECTED, URHO3D_HANDLER(P2PMultiplayer, HandleClientConnected));
     SubscribeToEvent(E_CLIENTDISCONNECTED, URHO3D_HANDLER(P2PMultiplayer, HandleClientDisconnected));
+    SubscribeToEvent(E_HTTPREQUESTFINISHED, URHO3D_HANDLER(P2PMultiplayer, HandleHttpResponse));
 //    SubscribeToEvent(refreshServerList_, "Released", URHO3D_HANDLER(LANDiscovery, HandleDoNetworkDiscovery));
 }
 
@@ -160,6 +162,7 @@ void P2PMultiplayer::HandleStartP2PSession(StringHash eventType, VariantMap& eve
 {
     URHO3D_LOGINFO("HandleStartP2PSession");
     GetSubsystem<Network>()->StartP2PSession(scene_);
+    GetSubsystem<Network>()->MakeHttpRequest("http://frameskippers.com:82/?guid=" + GetSubsystem<Network>()->P2PGetGUID());
 }
 
 void P2PMultiplayer::HandleJoinP2PSession(StringHash eventType, VariantMap& eventData)
@@ -182,14 +185,25 @@ void P2PMultiplayer::HandleUnready(StringHash eventType, VariantMap& eventData)
 
 void P2PMultiplayer::HandleUpdate(StringHash eventType, VariantMap& eventData)
 {
+    if (cameraNode_) {
+        cameraNode_->LookAt(ball_->GetPosition());
+    }
+    using namespace Update;
     static int i = 0;
     auto input = GetSubsystem<Input>();
-    if (input->GetKeyDown(KEY_R) && GetSubsystem<Network>()->P2PIsHostSystem()) {
-        if (body_) {
-            body_->SetLinearVelocity(Vector3(0, 2, 0));
-        }
+    float timestep = eventData[P_TIMESTEP].GetFloat();
+    static float gametime;
+    gametime += timestep * 10;
+
+    if (GetSubsystem<Network>()->P2PIsHostSystem()) {
+        //if (body_) {
+        //    body_->ApplyImpulse(Vector3(0, 10, 0));
+        //}
+        ball_->SetWorldPosition(Vector3(0, Sin(gametime) * 5 + 6, 0));
+        body_->SetLinearVelocity(Vector3(0, 0, 0));
     }
-    if (timer_.GetMSec(false) > 500) {
+
+    if (timer_.GetMSec(false) > 2000) {
         i++;
         timer_.Reset();
 //        URHO3D_LOGINFO(" ");
@@ -213,6 +227,9 @@ void P2PMultiplayer::HandleUpdate(StringHash eventType, VariantMap& eventData)
 //        URHO3D_LOGINFO("--------");
 //        GetSubsystem<Network>()->P2PShowReadyStatus();
 //        URHO3D_LOGINFO("");
+
+        // Just query for the newer P2P session
+        GetSubsystem<Network>()->MakeHttpRequest("http://frameskippers.com:82/guid.txt");
     }
 }
 
@@ -221,6 +238,7 @@ void P2PMultiplayer::Init()
 //    GetSubsystem<Network>()->SetNATServerInfo("frameskippers.com", 61111);
     GetSubsystem<Network>()->SetNATServerInfo("frameskippers.com", 61111);
     GetSubsystem<Network>()->P2PConnectNAT("frameskippers.com", 61111);
+    GetSubsystem<Network>()->SetUpdateFps(30);
 }
 
 //
@@ -348,6 +366,7 @@ void P2PMultiplayer::CreateScene()
 
             auto* body = floorNode->CreateComponent<RigidBody>();
             body->SetFriction(1.0f);
+            body->SetRestitution(0.5);
             auto* shape = floorNode->CreateComponent<CollisionShape>();
             shape->SetBox(Vector3::ONE);
         }
@@ -368,6 +387,7 @@ void P2PMultiplayer::CreateScene()
 
     // Create the scene node & visual representation. This will be a replicated object
     Node* ballNode = scene_->CreateChild("Ball");
+    ball_ = ballNode;
     ballNode->SetPosition(Vector3(0, 10, 0));
     ballNode->SetScale(0.5f);
     auto* ballObject = ballNode->CreateComponent<StaticModel>();
@@ -378,6 +398,7 @@ void P2PMultiplayer::CreateScene()
     auto* body = ballNode->CreateComponent<RigidBody>();
     body->SetMass(1.0f);
     body->SetFriction(1.0f);
+    body->SetRestitution(1);
     body_ = body;
     // In addition to friction, use motion damping so that the ball can not accelerate limitlessly
 //    body->SetLinearDamping(0.5f);
@@ -472,4 +493,11 @@ void P2PMultiplayer::HandleClientDisconnected(StringHash eventType, VariantMap&
 void P2PMultiplayer::HandleResetHost(StringHash eventType, VariantMap& eventData)
 {
     GetSubsystem<Network>()->P2PResetHost();
+}
+
+void P2PMultiplayer::HandleHttpResponse(StringHash eventType, VariantMap& eventData)
+{
+    using namespace HttpRequestFinished;
+    //URHO3D_LOGINFO("Response got: " + eventData[P_ADDRESS].GetString() + " => " + eventData[P_RESPONSE].GetString());
+    guid_->SetText(eventData[P_RESPONSE].GetString());
 }

+ 3 - 0
Source/Samples/54_P2PMultiplayer/P2PMultiplayer.h

@@ -102,6 +102,8 @@ private:
 
     void HandleResetHost(StringHash eventType, VariantMap& eventData);
 
+    void HandleHttpResponse(StringHash eventType, VariantMap& eventData);
+
     Timer timer_;
 //    /// Stop server
 //	void HandleStopServer(StringHash eventType, VariantMap& eventData);
@@ -122,4 +124,5 @@ private:
     SharedPtr<Text> myGuid_;
     SharedPtr<Text> hostGuid_;
     SharedPtr<RigidBody> body_;
+    SharedPtr<Node> ball_;
 };

+ 2 - 1
Source/ThirdParty/SLikeNet/CMakeLists.txt

@@ -16,7 +16,7 @@ set (TARGET_NAME SLikeNet)
 # Disable unneeded modules
 add_definitions (-DRAKNET_ENABLE_STATIC -D_RAKNET_SUPPORT_NatTypeDetectionServer=0 -D_RAKNET_SUPPORT_UDPForwarder=0 -D_RAKNET_SUPPORT_TwoWayAuthentication=0)
 add_definitions (-D_RAKNET_SUPPORT_CloudClient=0 -D_RAKNET_SUPPORT_CloudServer=0 -D_RAKNET_SUPPORT_ConnectionGraph2=0 -D_RAKNET_SUPPORT_NatPunchthroughServer=0)
-add_definitions (-D_RAKNET_SUPPORT_RelayPlugin=0 -D_RAKNET_SUPPORT_LibVoice=0 -D_RAKNET_SUPPORT_DynDNS=0 -D_RAKNET_SUPPORT_HTTPConnection2=0 -D_RAKNET_SUPPORT_HTTPConnection=0)
+add_definitions (-D_RAKNET_SUPPORT_RelayPlugin=0 -D_RAKNET_SUPPORT_LibVoice=0 -D_RAKNET_SUPPORT_DynDNS=0)
 add_definitions (-D_RAKNET_SUPPORT_EmailSender=0 -D_RAKNET_SUPPORT_UDPProxyClient=0 -D_RAKNET_SUPPORT_UDPProxyCoordinator=0 -D_RAKNET_SUPPORT_TeamManager=0 -D_RAKNET_SUPPORT_TeamBalancer=0)
 add_definitions (-D_RAKNET_SUPPORT_NatTypeDetectionClient=0 -D_RAKNET_SUPPORT_ConnectionGraph2=0 -D_RAKNET_SUPPORT_FullyConnectedMesh=0 -D_RAKNET_SUPPORT_TelnetTransport=0)
 add_definitions (-D_RAKNET_SUPPORT_DirectoryDeltaTransfer=0 -D_RAKNET_SUPPORT_FileOperations=0 -D_RAKNET_SUPPORT_UDPProxyServer=0)
@@ -30,6 +30,7 @@ add_definitions (-D_RAKNET_SUPPORT_FullyConnectedMesh2=1)
 add_definitions (-D_RAKNET_SUPPORT_PacketLogger=1)
 add_definitions (-D_RAKNET_SUPPORT_ReplicaManager3=1)
 add_definitions (-D_RAKNET_SUPPORT_ReadyEvent=1)
+add_definitions (-D_RAKNET_SUPPORT_HTTPConnection2=1 -D_RAKNET_SUPPORT_HTTPConnection=1)
 
 if (URHO3D_LIB_TYPE STREQUAL SHARED)
     add_definitions(-D_RAKNET_DLL=1)

+ 2 - 0
Source/Urho3D/Network/Connection.h

@@ -40,6 +40,8 @@ namespace SLNet
     class FullyConnectedMesh2;
     class ReadyEvent;
     class ConnectionGraph2;
+    class HTTPConnection2;
+    class TCPInterface;
 }
 
 namespace Urho3D

+ 55 - 2
Source/Urho3D/Network/Network.cpp

@@ -47,6 +47,8 @@
 #include <SLikeNet/BitStream.h>
 #include <SLikeNet/ReadyEvent.h>
 #include <SLikeNet/ConnectionGraph2.h>
+#include "SLikeNet/HTTPConnection2.h"
+#include "SLikeNet/TCPInterface.h"
 
 #ifdef SendMessage
 #undef SendMessage
@@ -221,6 +223,11 @@ Network::Network(Context* context) :
     rakPeer_->AttachPlugin(readyEvent_);
     connectionGraph2_ = SLNet::ConnectionGraph2::GetInstance();
     rakPeer_->AttachPlugin(connectionGraph2_);
+    httpConnection2_ = SLNet::HTTPConnection2::GetInstance();
+    tcp_ = SLNet::TCPInterface::GetInstance();
+    tcp_->AttachPlugin(httpConnection2_);
+
+    tcp_->Start(0, 0, 1);
 
     rakPeer_->SetTimeoutTime(SERVER_TIMEOUT_TIME, SLNet::UNASSIGNED_SYSTEM_ADDRESS);
     rakPeerClient_->SetTimeoutTime(SERVER_TIMEOUT_TIME, SLNet::UNASSIGNED_SYSTEM_ADDRESS);
@@ -311,6 +318,7 @@ Network::~Network()
     SLNet::FullyConnectedMesh2::DestroyInstance(fullyConnectedMesh2_);
     SLNet::ReadyEvent::DestroyInstance(readyEvent_);
     SLNet::ConnectionGraph2::DestroyInstance(connectionGraph2_);
+    SLNet::HTTPConnection2::DestroyInstance(httpConnection2_);
 
     rakPeer_ = nullptr;
     rakPeerClient_ = nullptr;
@@ -720,8 +728,11 @@ SharedPtr<HttpRequest> Network::MakeHttpRequest(const String& url, const String&
     URHO3D_PROFILE(MakeHttpRequest);
 
     // The initialization of the request will take time, can not know at this point if it has an error or not
-    SharedPtr<HttpRequest> request(new HttpRequest(url, verb, headers, postData));
-    return request;
+    //SharedPtr<HttpRequest> request(new HttpRequest(url, verb, headers, postData));
+    //return request;
+    SLNet::RakString rsRequest = SLNet::RakString::FormatForGET(url.CString());
+    httpConnection2_->TransmitRequest(rsRequest, "frameskippers.com", 82, true);
+    return nullptr;
 }
 
 void Network::BanAddress(const String& address)
@@ -1187,6 +1198,8 @@ void Network::Update(float timeStep)
             rakPeerClient_->DeallocatePacket(packet);
         }
     }
+
+    HandleTcpResponse();
 }
 
 void Network::PostUpdate(float timeStep)
@@ -1277,6 +1290,8 @@ void Network::OnServerConnected(const SLNet::AddressOrGUID& address)
 
 void Network::OnServerDisconnected()
 {
+    // TODO dont destroy server connection when one of the peers disconnects
+    return;
     // Differentiate between failed connection, and disconnection
     bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
     serverConnection_.Reset();
@@ -1401,6 +1416,44 @@ void Network::P2PResetHost()
     fullyConnectedMesh2_->ResetHostCalculation();
 }
 
+void Network::HandleTcpResponse()
+{
+    // The following code is TCP operations for talking to the master server, and parsing the reply
+    SLNet::SystemAddress sa;
+    // This is kind of crappy, but for TCP plugins, always do HasCompletedConnectionAttempt, then Receive(), then HasFailedConnectionAttempt(),HasLostConnection()
+    sa = tcp_->HasCompletedConnectionAttempt();
+    SLNet::Packet* packet;
+    for (packet = tcp_->Receive(); packet; tcp_->DeallocatePacket(packet), packet = tcp_->Receive())
+        ;
+    sa = tcp_->HasFailedConnectionAttempt();
+    sa = tcp_->HasLostConnection();
+
+    SLNet::RakString stringTransmitted;
+    SLNet::RakString hostTransmitted;
+    SLNet::RakString responseReceived;
+    SLNet::SystemAddress hostReceived;
+    ptrdiff_t contentOffset;
+    if (httpConnection2_->GetResponse(stringTransmitted, hostTransmitted, responseReceived, hostReceived, contentOffset))
+    {
+        if (responseReceived.IsEmpty() == false)
+        {
+            if (contentOffset == -1)
+            {
+                // No content
+                printf(responseReceived.C_String());
+            }
+            else
+            {
+                VariantMap data = GetEventDataMap();
+                data[HttpRequestFinished::P_ADDRESS] = "123";
+                data[HttpRequestFinished::P_RESPONSE] = String(responseReceived.C_String() + contentOffset);
+                SendEvent(E_HTTPREQUESTFINISHED, data);
+                URHO3D_LOGINFO("Response got: " + String(responseReceived.C_String() + contentOffset));
+            }
+        }
+    }
+}
+
 void RegisterNetworkLibrary(Context* context)
 {
     NetworkPriority::RegisterObject(context);

+ 4 - 0
Source/Urho3D/Network/Network.h

@@ -160,6 +160,8 @@ private:
     /// All incoming packages are handled here.
     void HandleIncomingPacket(SLNet::Packet* packet, bool isServer);
 
+    void HandleTcpResponse();
+
     /// SLikeNet peer instance for server connection.
     SLNet::RakPeerInterface* rakPeer_;
     /// SLikeNet peer instance for client connection.
@@ -212,6 +214,8 @@ private:
     bool natPunchtroughAttempt_;
     SLNet::ReadyEvent *readyEvent_;
     SLNet::ConnectionGraph2 *connectionGraph2_;
+    SLNet::HTTPConnection2 *httpConnection2_;
+    SLNet::TCPInterface *tcp_;
     String hostGuid_;
 };
 

+ 6 - 0
Source/Urho3D/Network/NetworkEvents.h

@@ -143,4 +143,10 @@ URHO3D_EVENT(E_NATMASTERCONNECTIONSUCCEEDED, NetworkNatMasterConnectionSucceeded
     URHO3D_PARAM(P_PORT, Port);         // int
 }
 
+URHO3D_EVENT(E_HTTPREQUESTFINISHED, HttpRequestFinished)
+{
+    URHO3D_PARAM(P_ADDRESS, Address);   // String
+    URHO3D_PARAM(P_RESPONSE, Response);         // int
+}
+
 }