簡體   English   中英

C ++ TCP套接字插件

[英]C++ TCP Socket Plugin

我目前正在使用仿真引擎VBS2,正在嘗試編寫TCP套接字插件。 我有一個客戶端應用程序,我想連接到插件並發送一條消息。 如果我發布現有的插件代碼,這可能更有意義:

#include <windows.h>
#include "VBSPlugin.h"

// Command function declaration
typedef int (WINAPI * ExecuteCommandType)(const char *command, char *result, int resultLength);

// Command function definition
ExecuteCommandType ExecuteCommand = NULL;

// Function that will register the ExecuteCommand function of the engine
VBSPLUGIN_EXPORT void WINAPI RegisterCommandFnc(void *executeCommandFnc)
{
  ExecuteCommand = (ExecuteCommandType)executeCommandFnc;
}

// This function will be executed every simulation step (every frame) and took a part     in the simulation procedure.
// We can be sure in this function the ExecuteCommand registering was already done.
// deltaT is time in seconds since the last simulation step
VBSPLUGIN_EXPORT void WINAPI OnSimulationStep(float deltaT)
{
  //{ Sample code:
ExecuteCommand("0 setOvercast 1", NULL, 0);
  //!}
}

// This function will be executed every time the script in the engine calls the script function "pluginFunction"
// We can be sure in this function the ExecuteCommand registering was already done.
// Note that the plugin takes responsibility for allocating and deleting the returned string
VBSPLUGIN_EXPORT const char* WINAPI PluginFunction(const char *input)
{
  //{ Sample code:
  static const char result[]="[1.0, 3.75]";
  return result;
  //!}
}

// DllMain
BOOL WINAPI DllMain(HINSTANCE hDll, DWORD fdwReason, LPVOID lpvReserved)
{
   switch(fdwReason)
   {
      case DLL_PROCESS_ATTACH:
         OutputDebugString("Called DllMain with DLL_PROCESS_ATTACH\n");
         break;
      case DLL_PROCESS_DETACH:
         OutputDebugString("Called DllMain with DLL_PROCESS_DETACH\n");
     break;
      case DLL_THREAD_ATTACH:
         OutputDebugString("Called DllMain with DLL_THREAD_ATTACH\n");
         break;
      case DLL_THREAD_DETACH:
         OutputDebugString("Called DllMain with DLL_THREAD_DETACH\n");
         break;
   }
   return TRUE;
}

發送到插件的消息將通過作為參數傳遞給ExecuteCommand()在OnSimulationStep()函數中使用。 但是,在這里進行阻塞也要特別小心,因為必須允許OnSimulationStep()函數運行每個模擬步驟。

我已經盯着這幾天了,並嘗試查看winsock教程,但是我不是C ++程序員,所以感覺很困。 請任何人友好地給我一些正確的方向指示?

在此先感謝您,所有建議都將不勝感激。

我個人會使用boost :: asio來節省自己處理異步IO的所有麻煩。

它使用起來相對簡單,並且在插件環境中也很好用-我做過類似的事情(在VBS2中也是如此)。

當您的插件必須在短時間內處理數據並且擔心winsock send函數可能會阻塞時,您可以將數據排隊或編寫一種僅寫入重要數據的機制(如果可以選擇)。

一種選擇是插件中的隊列和工作線程,該線程將數據從隊列中泵送到套接字。 使用附加線程,您可以僅使用潛在的阻塞調用。 如果阻塞的調用對您來說是個問題,則可以將套接字設置為非阻塞模式,然后與WSAAsyncSelect等待一個事件,該事件指示您可以再次寫入對等方。

您可以實現一個TCP服務器,將傳入消息存儲在有序列表中。 然后,在每個OnSimulationStep中,向TCP服務器查詢接收的消息,然后通過ExecuteCommand將它們應用於VBS2。

請記住,始終在調用OnSimulationStep的線程中使用ExecuteCommand。 這意味着您將無法直接在TCP服務器中執行傳入消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM