命名管道通信
大家看下我这代码为什么不能在两台机器上通信 错误提示为 拒绝访问
服务器端:
#include<iostream>
#include<windows.h>
#include<string.h>
using namespace std;
int main( void )
{
HANDLE pipehandle;
char buf[ 256 ];
DWORD bytesRead;
if( ( pipehandle = CreateNamedPipe( "\\\\.\\pipe\\cao", PIPE_ACCESS_DUPLEX , PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 0, 0, 5000, NULL ) ) == INVALID_HANDLE_VALUE )
{
printf( "CreateNamedPipe failed with error %d/n", GetLastError() );
system( "pause" );
return 0;
}
printf( "server is running\n" );
if( ConnectNamedPipe( pipehandle, NULL ) == 0 )
{
printf( "connectNamedPipe failed with error %d\n", GetLastError() );
CloseHandle( pipehandle );
system( "pause" );
return 0;
}
if( ReadFile( pipehandle, buf, strlen( buf ), &bytesRead, NULL ) == 0 )
{
printf( "ReadFile failed with error %d/n", GetLastError() );
CloseHandle( pipehandle );
system( "pause" );
return 0;
}
//buf[bytesRead] = '\0';
printf( "%s\n", buf );
if ( DisconnectNamedPipe( pipehandle ) == 0 )
{
printf( "DisconnectNamedPipe failed with error %d\n", GetLastError() );
CloseHandle( pipehandle );
system( "pause" );
return 0;
}
system( "pause" );
return 0;
}
客户端:
#include<iostream>
#include<windows.h>
#include<string.h>
using namespace std;
int main( void )
{
HANDLE pipehandle;
DWORD writesbytes;
char buff[ 256 ];
if( WaitNamedPipe("\\\\apical-3bbb979\\pipe\\cao", NMPWAIT_WAIT_FOREVER ) == 0 )
{
printf( "WaitNamedPipe failed with error %d\n", GetLastError() );
system( "pause" );
return 0;
}
else
{
printf("connect .......\n");
}
if( ( pipehandle = CreateFile( "\\\\apical-3bbb979\\pipe\\cao", GENERIC_READ | GENERIC_WRITE, 0, ( LPSECURITY_ATTRIBUTES )NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, ( HANDLE )NULL ) ) == INVALID_HANDLE_VALUE )
{
printf( "CreateFile failed with error %d\n", GetLastError() );
system( "pause" );
return 0;
}
else
{
printf("opened pleass input num\n");
}
ZeroMemory( &buff, sizeof( buff ) );
gets( buff );
if( WriteFile( pipehandle, buff, strlen( buff ) + 1, &writesbytes, NULL ) == 0 )
{
printf( "WriteFile failed with error %d\n", GetLastError() );
CloseHandle( pipehandle );
system( "pause" );
return 0;
}
printf( "write %d bytes", writesbytes );
CloseHandle( pipehandle );
system( "pause" );
return 0;
}
apical-3bbb979是我的计算机名
在本机可以 在局域网上两台机器上就不行了 可以监听到 但是不能打开管道