我创建了NamedPipe C ++服务器和C#客户端。客户端和服务器成功连接并读取双方的等待数据。
现在我想从服务器向客户端发送数据,但是由于 WriteFile API被阻止,服务器无法写入数据。
您能在我想念的地方帮助我吗? 要么 还有其他方法吗?
C ++服务器代码
HANDLE _hPipe = INVALID_HANDLE_VALUE, hThread = NULL;
BOOL bIsNamedPipeConnected = FALSE;
DWORD dwThreadId = 0;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\TestNamePipe");
bool bIsNamedPipeReaderThreadRunnig = false;
bool bStopNamedPipeReaderThread = false;
char _logbuffer[3000];
#define BUFSIZE 1024
DWORD WINAPI InstanceThreadEx(LPVOID);
DWORD WINAPI InstanceThreadEx(LPVOID lpvParam)
{
bIsNamedPipeConnected = ConnectNamedPipe(_hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
bIsNamedPipeReaderThreadRunnig = true;
DWORD cbBytesRead = 0;
while (bStopNamedPipeReaderThread == false && bIsNamedPipeConnected)
{
char readBuffer[BUFSIZE];
DWORD cbWritten = 0;
bool bSuccess = ReadFile(_hPipe,readBuffer,BUFSIZE ,&cbWritten, NULL);
if (!bSuccess)
{
sprintf_s(_logbuffer, "Error in writing buffer to Byte Written = %d", cbWritten);
printf(_logbuffer);
}
}
bIsNamedPipeReaderThreadRunnig = false;
return 1;
}
void CMFCApplication1Dlg::OnBnClickedWrite()
{
char pchReply[BUFSIZE];
memcpy(pchReply, "HelloWord", 9);
DWORD cbWritten = 0;
bool bSuccess = WriteFile(_hPipe,pchReply,BUFSIZE,&cbWritten, NULL);
}
void CMFCApplication1Dlg::OnBnClickedConnect()
{
printf("Connecting Named Pipe");
bIsNamedPipeConnected = false;
hThread = NULL;
_hPipe = CreateNamedPipe(
lpszPipename, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
1, // max. instances
BUFSIZE, // output buffer size
BUFSIZE, // input buffer size
0, // client time-out
NULL); // default security attribute
if (_hPipe == INVALID_HANDLE_VALUE)
{
return;
}
hThread = CreateThread(NULL, 0, InstanceThreadEx, (LPVOID)_hPipe, 0, &dwThreadId);
}
C#客户端
int bufferSize = 1024;
NamedPipeClientStream _pipeClient;
private void initializeServer()
{
_pipeClient = new NamedPipeClientStream(".", "TestNamePipe", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
_pipeClient.Connect();
byte[] data = new byte[bufferSize];
BeginRead(data);
}
public void BeginRead(byte [] message)
{
try
{
_pipeClient.BeginRead(message, 0, bufferSize, EndReadCallBack, message);
}
catch
{
//suppress exception
}
}
private void EndReadCallBack(IAsyncResult result)
{
var readBytes = _pipeClient.EndRead(result);
if (readBytes > 0)
{
byte [] messageInfo = (byte [])result.AsyncState;
if (!_pipeClient.IsMessageComplete)
{
BeginRead(messageInfo);
}
else
{
var message = messageInfo.ToString().TrimEnd('\0');
textBox1.Text = message;
byte[] data = new byte[bufferSize];
BeginRead(data);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
byte [] data = Encoding.UTF8.GetBytes(this.textBox1.Text);
_pipeClient.Write(data, 0, data.Length);
}