命名管道c#服务器c++ .dll客户端不工作
本文关键字:dll 客户端 工作 c++ 服务器 管道 | 更新日期: 2023-09-27 18:17:00
所以我试图使用命名管道在c#服务器和我将注入的c++ .dll客户端之间进行通信。当使用c++控制台应用程序时,我的命名管道工作正常,但当我在。dll中使用相同的方法时,服务器和客户端连接良好,但当我尝试使用NamedPipeServerStream.Write()时,我的c#应用程序冻结。如果有关系的话,它们都是x64。
知道为什么吗?
c#服务器 Thread ServerThread;
private static NamedPipeServerStream _server;
private void Form1_Load(object sender, EventArgs e)
{
ServerThread = new Thread(ServerThreadSub);
ServerThread.Start();
}
void ServerThreadSub()
{
while (true)
{
_server = new NamedPipeServerStream("ConsolePipe", PipeDirection.Out, 1, PipeTransmissionMode.Message);
_server.WaitForConnection();
do
{
} while (_server.IsConnected);
_server.Close();
}
}
private void text_CurrentCommand_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
if (text_CurrentCommand.Text != "")
{
if (_server.IsConnected)
{
try
{
byte[] buff = Encoding.UTF8.GetBytes(text_CurrentCommand.Text);
_server.Write(buff, 0, buff.Length); //Freezes here
}
catch
{
Log("Client Disconnected, Command Not Processed.");
}
}
else
{
Log("Command Not Processed. Client Not Connected.");
}
}
e.SuppressKeyPress = true;
}
}
c++客户#define PIPE_NAME L"''''.''pipe''ConsolePipe"
#define BUFF_SIZE 1024
HANDLE hPipe;
DWORD WINAPI Main(LPVOID threadArgs)
{
while (true)
{
do
{
Sleep(1000);
hPipe = CreateFile(PIPE_NAME, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);
if (hPipe == NULL || hPipe == INVALID_HANDLE_VALUE) DeleteFile(PIPE_NAME);
} while (hPipe == NULL || hPipe == INVALID_HANDLE_VALUE);
DWORD mode = PIPE_READMODE_MESSAGE;
SetNamedPipeHandleState(hPipe, &mode, nullptr, nullptr);
bool success = false;
DWORD read;
while (true)
{
char chBuff[BUFF_SIZE];
success = ReadFile(hPipe, chBuff, (DWORD)strlen(chBuff), &read, nullptr);
if (success)
{
}
if (!success) break;
}
}
return 0;
}
另一个查询我有那不是很重要,有任何方法获得NamedPipeServerStream。IsConnected刷新而不执行Read()或Write()?
c:如果你正在创建一个dll,那么我建议你使用 DllMain()
作为入口点,这可能是你的程序不工作的主要原因之一
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpReserved ) // reserved
{
// Perform actions based on the reason for calling.
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
// Initialize once for each new process.
// Return FALSE to fail DLL load.
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
break;
}
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
更多信息https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx