繁体   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