系统相关
首页 > 系统相关> > 进程间通信-命名管道-服务器端与客户端代码示范

进程间通信-命名管道-服务器端与客户端代码示范

作者:互联网

进程间通信-命名管道-服务器端与客户端代码示范

 

服务器端:

void CNamedPipeServerDlg::OnBnClickedButtonListen()
{
	// TODO: 在此添加控件通知处理程序代码
	m_hPipe = CreateNamedPipe("\\\\.\\Pipe\\NamedPipeSample", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 0, 0, 1000, NULL);
	if (m_hPipe == INVALID_HANDLE_VALUE)
	{
		m_Log = "创建命名管道失败!\r\n";
		UpdateData(FALSE);
		return;

	}
	else
	{
		m_Log = "创建命名管道成功咯。txwtech\r\n";
		UpdateData(FALSE);
		AfxBeginThread(ListenProc,this);
	}
}


//UINT CNamedPipeServerDlg::ListenProc(LPVOID lpVoid)
//{
//	return 0;
//}
UINT ListenProc(LPVOID lpVoid)
{
	char buffer[1024];
	DWORD dwReadBytes;
	CNamedPipeServerDlg* pDlg = (CNamedPipeServerDlg*)lpVoid;
	if (ConnectNamedPipe(pDlg->m_hPipe, NULL) == FALSE)
	{
		CloseHandle(pDlg->m_hPipe);
		pDlg->m_Log += "与命名管道客户端建立连接失败\r\n";
		pDlg->m_editLog.SetWindowTextA(pDlg->m_Log);//线程里面不能使用UpdateDate(FALSE);
		return 0;
	}
	if (ReadFile(pDlg->m_hPipe, buffer, sizeof(buffer), &dwReadBytes, NULL) == FALSE)
	{
		CloseHandle(pDlg->m_hPipe);
		pDlg->m_Log += "从管道读取数据失败!txwtech\r\n";
	}
	else
	{
		buffer[dwReadBytes] = '\0';
		pDlg->m_Log += "txwtech接受到客户端命名管道发送的数据=\r\n";
		pDlg->m_Log += CString(buffer);
	}
	if (DisconnectNamedPipe(pDlg->m_hPipe) == FALSE)
	{
		pDlg->m_Log += "txwtech终止连接失败\r\n";
	}
	else
	{
		CloseHandle(pDlg->m_hPipe);
		pDlg->m_Log += "txwtech成功终止连接\r\n";
	}
	pDlg->m_editLog.SetWindowTextA(pDlg->m_Log);
	return 1;
}

客户端:

void CNamedPipeClientDlg::OnBnClickedButtonConnect()
{
	// TODO: 在此添加控件通知处理程序代码
	CString content = "{测试数据,我是命名管道客户端}\r\n";
	DWORD dwWriteBytes;
	if (WaitNamedPipe("\\\\.\\Pipe\\NamedPipeSample", NMPWAIT_WAIT_FOREVER) == FALSE)
	{
		m_Log = "等待连接失败!\r\n";
		UpdateData(FALSE);
		return;
	}
	HANDLE hPipe = CreateFile("\\\\.\\Pipe\\NamedPipeSample",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
	if (hPipe == INVALID_HANDLE_VALUE)
	{
		m_Log += "打开命名管道失败\r\n";
		UpdateData(FALSE);
		return;
	}
	else
		m_Log += "打开命名管道成功\r\n";

	if (!WriteFile(hPipe, content, content.GetLength(), &dwWriteBytes, NULL))
		m_Log += "向命名管道写入数据失败!\r\n";
	else
	{
		m_Log += "向命名管道写入数据成功\r\n";
	}
	UpdateData(FALSE);
	CloseHandle(hPipe);
}

 

标签:FALSE,Log,hPipe,间通信,管道,pDlg,命名,客户端,服务器端
来源: https://blog.csdn.net/txwtech/article/details/90138453