当前位置:   article > 正文

UE5- c++ websocket客户端写法_ue5 websocket

ue5 websocket

# 实现目标

  • ue5 c++ 实现socket客户端,读取服务端数据,并进行解析

#实现步骤

  1. {projectName}.Build.cs里增加 "WebSockets","JsonUtilities", "Json"配置信息,最终输出如下:
    1. using UnrealBuildTool;
    2. public class myue521 : ModuleRules
    3. {
    4. public myue521(ReadOnlyTargetRules Target) : base(Target)
    5. {
    6. PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
    7. PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore"
    8. , "HeadMountedDisplay", "EnhancedInput"
    9. , "WebSockets","JsonUtilities", "Json"});
    10. }
    11. }

    说明,其中myue521是我的模块名,文件名为myue521.Build.cs。 新增的模块:"WebSockets","JsonUtilities", "Json"。

  2. 准备实现自己的webscoket_client。具体操作步骤如下:

    1. ue5中自定义类,父类设置为UGameInstance,我这命名为UUWebSocketGameInstance

    2. 在UUWebSocketGameInstance.h里新增如下方法。

      1. 其中init和 Shutdown方法是在父类UGameInstance中定义的,我们这里覆盖它;

      2. WebSocket用来标识我们代码生成的socket,计划在init里初始化,在Shutdown里销毁

      3. OnConnected、OnConnectionError、OnClosed、OnMessage、OnMessageSent用来处理socket消息,具体看后买你的代码实现。

    3. 在UUWebSocketGameInstance.cpp里实现已经生命的方法。

      1. // Fill out your copyright notice in the Description page of Project Settings.
      2. #include "UWebSocketGameInstance.h"
      3. #include "WebSockets/Public/WebSocketsModule.h"
      4. #include "WebSockets/Public/IWebSocket.h"
      5. #include "Templates/SharedPointer.h"
      6. void UUWebSocketGameInstance::Init() {
      7. Super::Init();
      8. if (!FModuleManager::Get().IsModuleLoaded("WebSockets")) {
      9. FModuleManager::Get().LoadModule("WebSockets");
      10. }
      11. WebSocket = FWebSocketsModule::Get().CreateWebSocket("ws://127.0.0.1:8081/webSocketServer/ue");
      12. WebSocket->OnConnected().AddUObject(this, &UUWebSocketGameInstance::OnConnected);
      13. WebSocket->OnConnectionError().AddUObject(this, &UUWebSocketGameInstance::OnConnectionError);
      14. WebSocket->OnClosed().AddUObject(this, &UUWebSocketGameInstance::OnClosed);
      15. WebSocket->OnMessage().AddUObject(this, &UUWebSocketGameInstance::OnMessage);
      16. WebSocket->OnMessageSent().AddUObject(this, &UUWebSocketGameInstance::OnMessageSent);
      17. WebSocket->Connect();
      18. }
      19. void UUWebSocketGameInstance::Shutdown() {
      20. if (WebSocket->IsConnected()) {
      21. WebSocket->Close();
      22. }
      23. Super::Shutdown();
      24. }
      25. void UUWebSocketGameInstance::OnConnected()
      26. {
      27. UE_LOG(LogTemp, Warning, TEXT("%s"), *FString(__FUNCTION__));
      28. GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Green, "Successfully Connected");
      29. }
      30. void UUWebSocketGameInstance::OnConnectionError(const FString& Error)
      31. {
      32. UE_LOG(LogTemp, Warning, TEXT("%s Error:%s"), *FString(__FUNCTION__), *Error);
      33. }
      34. void UUWebSocketGameInstance::OnClosed(int32 StatusCode, const FString& Reason, bool bWasClean)
      35. {
      36. UE_LOG(LogTemp, Warning, TEXT("%s StatusCode:%d Reason:%s bWasClean:%d"),
      37. *FString(__FUNCTION__), StatusCode, *Reason, bWasClean);
      38. }
      39. void UUWebSocketGameInstance::OnMessage(const FString& Message)
      40. {
      41. GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Cyan, FString::Printf(TEXT("%s Message:%s"), *FString(__FUNCTION__), *Message) );
      42. UE_LOG(LogTemp, Warning, TEXT("%s Message:%s"), *FString(__FUNCTION__), *Message);
      43. TSharedRef< TJsonReader<> > Reader = TJsonReaderFactory<>::Create(Message);
      44. TSharedPtr<FJsonObject> Root;
      45. if (FJsonSerializer::Deserialize(Reader, Root))
      46. {
      47. if (Root->HasField(TEXT("Topic"))) {
      48. FString Topic = Root->GetStringField(TEXT("Topic"));
      49. TSharedPtr<FJsonObject, ESPMode::ThreadSafe> Data = Root->GetObjectField(TEXT("Data"));
      50. // TSharedPtr<FJsonObject, ESPMode::ThreadSafe> ObjectField = Object->GetObjectField(TEXT("realtime"));
      51. FString KeyField = Data->GetStringField("Key");
      52. FString ValueField = Data->GetStringField("Value");
      53. GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Cyan, "Key: " + KeyField + ",Value:" + ValueField);
      54. }
      55. else {
      56. GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Cyan, "解析json异常");
      57. }
      58. }
      59. }
      60. void UUWebSocketGameInstance::OnMessageSent(const FString& MessageString)
      61. {
      62. UE_LOG(LogTemp, Warning, TEXT("%s MessageString:%s"), *FString(__FUNCTION__), *MessageString);
      63. }
      1. 其中UUWebSocketGameInstance::Init()里初始化了websocket,并配置监听方法

      2. UUWebSocketGameInstance::Shutdown()用来销毁生成的websocket

      3. UUWebSocketGameInstance::OnConnected(),UUWebSocketGameInstance::OnConnectionError,UUWebSocketGameInstance::OnClosed,UUWebSocketGameInstance::OnMessage,UUWebSocketGameInstance::OnMessageSent是用来处理绑定消息的。其中UUWebSocketGameInstance::OnMessage里的消息是json格式,具体格式见下面的备注1.

  3. 开始配置使用并调用方法。

    1. 自主调用可以在某个Character里通过如下代码进行调用。可以在自己的类里面调用。比如放到构造方法或者某个动作触发调用。

      1. void Amyue521Character::NotifyServer() {
      2. UUWebSocketGameInstance* GameInstance = Cast<UUWebSocketGameInstance>(GetGameInstance());
      3. if (GameInstance) {
      4. if (GameInstance->WebSocket->IsConnected()) {
      5. GameInstance->WebSocket->Send("FROM UnrealEngine 5");
      6. }
      7. }
      8. }
    2. 通过UE5的项目设置进行修改游戏实例。

  4. 备注

    1. 约定接收的json数据格式为

      {
          "Topic": "Unreal",
          "Data": {
              "Key": "mood",
              "Value": 1.0
          }
       }
  5. 总结

    1.  通过该例子我们学到了websocket,json的应用

    2. 还学到的两种打印log的方法

      1. GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Cyan, FString::Printf(TEXT("%s Message:%s"), *FString(__FUNCTION__), *Message) );
      2. UE_LOG(LogTemp, Warning, TEXT("%s Message:%s"), *FString(__FUNCTION__), *Message);
  6. 待解决的问题

    1. 为什么使用UGameInstance, UGameInstance在UE5中充当什么角色

    2. ULog 的使用,参考文档:http://www.bimant.com/blog/ue_log-crash-course/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/143507
推荐阅读
相关标签
  

闽ICP备14008679号