namedpipe传输数据失败,麻烦各位看看是什么有关问题

namedpipe传输数据失败,麻烦各位看看是什么问题。
for(;;)//创建namedpipe的服务器端代码
{
//create namedpipe client 
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 
PIPE_UNLIMITED_INSTANCES, // max. instances  
BUFSIZE, // output buffer size 
BUFSIZE, // input buffer size 
0, // client time-out 
&sa); // default security attribute 
if(hPipe != INVALID_HANDLE_VALUE) 
{
return -1;
}
MessageBox(NULL,TEXT("create namepipe successful"),NULL,NULL);

fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if(fConnected==TRUE)
{
MessageBox(NULL,TEXT("connect the namedpipe client"),NULL,NULL);
else
  {
CloseHandle(hPipe);
}
下面是传输 数据的线程,啊麻烦各位看看,哪里有错,谢谢~


DWORD WINAPI InstanceThread(LPVOID lpvParam)
// This routine is a thread processing function to read from and reply to a client
// via the open pipe connection passed from the main loop. Note this allows
// the main loop to continue executing, potentially creating more threads of
// of this procedure to run concurrently, depending on the number of incoming
// client connections.

#ifdef Debug_mode
MessageBox(NULL,_T("enter server thread"),NULL, NULL);
#endif
  HANDLE hHeap = GetProcessHeap();
  TCHAR* pchRequest = (TCHAR*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, BUFSIZE*sizeof(TCHAR));
  TCHAR* pchReply = (TCHAR*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, BUFSIZE*sizeof(TCHAR));

  DWORD cbBytesRead = 0, cbReplyBytes = 0, cbWritten = 0; 
  BOOL fSuccess = FALSE;
  HANDLE hPipe = NULL;

  // Do some extra error checking since the app will keep running even if this
  // thread fails.

  if (lpvParam == NULL)
  {
  // printf( "\nERROR - Pipe Server Failure:\n");
  // printf( " InstanceThread got an unexpected NULL value in lpvParam.\n");
  // printf( " InstanceThread exitting.\n");
  if (pchReply != NULL) HeapFree(hHeap, HEAP_ZERO_MEMORY, pchReply);
  if (pchRequest != NULL) HeapFree(hHeap,HEAP_ZERO_MEMORY, pchRequest);
  return (DWORD)-1;
  }

  if (pchRequest == NULL)
  {
  //printf( "\nERROR - Pipe Server Failure:\n");
  //printf( " InstanceThread got an unexpected NULL heap allocation.\n");
  //printf( " InstanceThread exitting.\n");
  if (pchReply != NULL) HeapFree(hHeap, 0, pchReply);
  return (DWORD)-1;
  }

  if (pchReply == NULL)
  {
  //printf( "\nERROR - Pipe Server Failure:\n");
  //printf( " InstanceThread got an unexpected NULL heap allocation.\n");
  //printf( " InstanceThread exitting.\n");
  if (pchRequest != NULL) HeapFree(hHeap, 0, pchRequest);
  return (DWORD)-1;
  }

  // Print verbose messages. In production code, this should be for debugging only.
  // printf("InstanceThread created, receiving and processing messages.\n");