所以我試圖使用命名管道在C#服務器和我將注入的C++ .dll客戶端之間進行通信。 我的命名管道在與C++控制檯應用程序一起使用時工作正常,但是當我在.dll中使用相同的方法時,服務器和客戶端連接正常,但是當我嘗試使用NamedPipeServerStream.Write()時,我的C#應用程序凍結。如果這很重要,它們都是x64。命名管道C#服務器C++ .dll客戶端不能正常工作?
任何想法爲什麼?
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無需執行讀取刷新( )或寫()?
在此先感謝C:
在ReadFile()調用中使用strlen(chBuff)是不正確的,它會生成一個完全隨機數。改用BUFF_SIZE。 –
好吧我會嘗試c: – Semyel
工作,非常感謝你! c: – Semyel