C ++ TCP套接字插件

时间:2011-05-11 14:20:12

标签: c++ windows sockets plugins tcp

我目前正在使用模拟引擎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 ++程序员而且感觉很困难。请有人愿意给我一些正确方向的指示吗?

在此先感谢,非常感谢所有建议。

3 个答案:

答案 0 :(得分:1)

我个人会使用boost :: asio来节省处理异步IO的所有麻烦。

使用相对简单,并且它在插件环境中运行良好 - 我做了类似的事情(也在VBS2中)。

答案 1 :(得分:0)

如果您的插件必须在短时间内处理数据,您担心winsock send函数可能会阻塞,您需要对数据进行排队或编写仅包含重要数据的机制写的,如果这是一个选项。

一个选项是插件中的队列和一个工作线程,用于将数据从队列泵送到套接字。使用附加线程,您可以使用潜在的阻止调用。如果阻塞调用对您来说是一个问题,您可以将套接字设置为非阻塞模式,并等待WSAAsyncSelect一个事件,表明您可以再次写入对等。

答案 2 :(得分:0)

您可以实现一个TCP服务器,它将传入的消息存储在有序列表中。在每个OnSimulationStep中,然后查询TCP服务器以获取收到的消息,并通过ExecuteCommand将它们应用于VBS2。

请记住在调用OnSimulationStep的线程中始终使用ExecuteCommand。这意味着您无法直接在TCP服务器中执行传入消息。