【发布时间】:2016-11-09 10:36:22
【问题描述】:
所以我正在尝试使用命名管道在我将注入的 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() 的情况下刷新?
提前致谢:
【问题讨论】:
-
在 ReadFile() 调用中使用 strlen(chBuff) 是不正确的,它会生成一个完全随机的数字。请改用 BUFF_SIZE。
-
好的,我试试 c:
-
成功了,非常感谢! c:
标签: c# c++ dll ipc named-pipes