我目前正在使用模拟引擎 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 中)。
关于C++ TCP 套接字插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5965782/