C++ C和x2B之间的通信(IPC)+;巨蟒
我有应用服务器(server.py)和C++作为客户端(client.exe)。Client.exe通过“命名管道”将变量发送到server.py 问题是当我从server.py中的client.exe发送例如“defaultmessagefromclient”时,仅产生“D”(仅发送第一个字符) 有人能帮我吗 C++ server.pyC++ C和x2B之间的通信(IPC)+;巨蟒,c++,python,windows,C++,Python,Windows,我有应用服务器(server.py)和C++作为客户端(client.exe)。Client.exe通过“命名管道”将变量发送到server.py 问题是当我从server.py中的client.exe发送例如“defaultmessagefromclient”时,仅产生“D”(仅发送第一个字符) 有人能帮我吗 C++ server.py from ctypes import * PIPE_ACCESS_DUPLEX = 0x3 PIPE_TYPE_MESSAGE = 0x4 PIPE_REA
from ctypes import *
PIPE_ACCESS_DUPLEX = 0x3
PIPE_TYPE_MESSAGE = 0x4
PIPE_READMODE_MESSAGE = 0x2
PIPE_WAIT = 0
PIPE_UNLIMITED_INSTANCES = 255
BUFSIZE = 4096
NMPWAIT_USE_DEFAULT_WAIT = 0
INVALID_HANDLE_VALUE = -1
ERROR_PIPE_CONNECTED = 535
MESSAGE = "Default answer from server\0"
szPipename = "\\\\.\\pipe\\mynamedpipe"
def ReadWrite_ClientPipe_Thread(hPipe):
chBuf = create_string_buffer(BUFSIZE)
cbRead = c_ulong(0)
while 1:
fSuccess = windll.kernel32.ReadFile(hPipe, chBuf, BUFSIZE,
byref(cbRead), None)
if ((fSuccess ==1) or (cbRead.value != 0)):
print chBuf.value
cbWritten = c_ulong(0)
fSuccess = windll.kernel32.WriteFile(hPipe,c_char_pc_char_p(MESSAGE),len(MESSAGE),byref(cbWritten),None)
else:
break
if ( (not fSuccess) or (len(MESSAGE) != cbWritten.value)):
print "Could not reply to the client's request from the pipe"
break
else:
print "Number of bytes written:", cbWritten.value
windll.kernel32.FlushFileBuffers(hPipe)
windll.kernel32.DisconnectNamedPipe(hPipe)
windll.kernel32.CloseHandle(hPipe)
return 0
def main():
THREADFUNC = CFUNCTYPE(c_int, c_int)
thread_func = THREADFUNC(ReadWrite_ClientPipe_Thread)
while 1:
hPipe = windll.kernel32.CreateNamedPipeA(szPipename,PIPE_ACCESS_DUPLEX,PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, NMPWAIT_USE_DEFAULT_WAIT,None)
if (hPipe == INVALID_HANDLE_VALUE):
print "Error in creating Named Pipe"
return 0
fConnected = windll.kernel32.ConnectNamedPipe(hPipe, None)
if ((fConnected == 0) and (windll.kernel32.GetLastError() == ERROR_PIPE_CONNECTED)):
fConnected = 1
if (fConnected == 1):
dwThreadId = c_ulong(0)
hThread = windll.kernel32.CreateThread(None, 0, thread_func, hPipe, 0, byref(dwThreadId))
if (hThread == -1):
print "Create Thread failed"
return 0
else:
windll.kernel32.CloseHandle(hThread)
else:
print "Could not connect to the Named Pipe"
windll.kernel32.CloseHandle(hPipe)
return 0
if __name__ == "__main__":
main()
客户端.cpp
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#define BUFSIZE 512
int _tmain(int argc, TCHAR *argv[])
{
HANDLE hPipe;
LPTSTR lpvMessage=TEXT("Default message from client.");
TCHAR chBuf[BUFSIZE];
BOOL fSuccess = FALSE;
DWORD cbRead, cbToWrite, cbWritten, dwMode;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe");
if( argc > 1 )
lpvMessage = argv[1];
// Try to open a named pipe; wait for it, if necessary.
while (1)
{
hPipe = CreateFile(
lpszPipename, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
// Break if the pipe handle is valid.
if (hPipe != INVALID_HANDLE_VALUE)
break;
// Exit if an error other than ERROR_PIPE_BUSY occurs.
if (GetLastError() != ERROR_PIPE_BUSY)
{
_tprintf( TEXT("Could not open pipe. GLE=%d\n"), GetLastError() );
return -1;
}
// All pipe instances are busy, so wait for 20 seconds.
if ( ! WaitNamedPipe(lpszPipename, 20000))
{
printf("Could not open pipe: 20 second wait timed out.");
return -1;
}
}
// The pipe connected; change to message-read mode.
dwMode = PIPE_READMODE_MESSAGE;
fSuccess = SetNamedPipeHandleState(
hPipe, // pipe handle
&dwMode, // new pipe mode
NULL, // don't set maximum bytes
NULL); // don't set maximum time
if ( ! fSuccess)
{
_tprintf( TEXT("SetNamedPipeHandleState failed. GLE=%d\n"), GetLastError() );
return -1;
}
// Send a message to the pipe server.
cbToWrite = (lstrlen(lpvMessage)+1)*sizeof(TCHAR);
_tprintf( TEXT("Sending %d byte message: \"%s\"\n"), cbToWrite, lpvMessage);
fSuccess = WriteFile(
hPipe, // pipe handle
lpvMessage, // message
cbToWrite, // message length
&cbWritten, // bytes written
NULL); // not overlapped
if ( ! fSuccess)
{
_tprintf( TEXT("WriteFile to pipe failed. GLE=%d\n"), GetLastError() );
return -1;
}
printf("\nMessage sent to server, receiving reply as follows:\n");
do
{
// Read from the pipe.
fSuccess = ReadFile(
hPipe, // pipe handle
chBuf, // buffer to receive reply
BUFSIZE*sizeof(TCHAR), // size of buffer
&cbRead, // number of bytes read
NULL); // not overlapped
if ( ! fSuccess && GetLastError() != ERROR_MORE_DATA )
break;
_tprintf( TEXT("\"%s\"\n"), chBuf );
} while ( ! fSuccess); // repeat loop if ERROR_MORE_DATA
if ( ! fSuccess)
{
_tprintf( TEXT("ReadFile from pipe failed. GLE=%d\n"), GetLastError() );
return -1;
}
CloseHandle(hPipe);
return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#定义BUFSIZE 512
int_tmain(int argc,TCHAR*argv[])
{
处理高压管道;
LPTSTR lpvMessage=TEXT(“来自客户端的默认消息”);
TCHAR chBuf[BUFSIZE];
boolfsuccess=FALSE;
DWORD cbRead、cbToWrite、CBWRITED、dwMode;
LPTSTR lpszPipename=TEXT(“\\\.\\pipe\\mynamedpipe”);
如果(argc>1)
lpvMessage=argv[1];
//尝试打开命名管道;如有必要,请等待它。
而(1)
{
hPipe=CreateFile(
lpszPipename,//管道名称
GENERIC_READ |//读写访问
你写什么,
0,//没有共享
NULL,//默认安全属性
打开现有管道,//打开现有管道
0,//默认属性
NULL);//没有模板文件
//如果管道控制柄有效,则断开。
if(hPipe!=无效的\u句柄\u值)
打破
//如果发生错误_PIPE _BUSY以外的错误,请退出。
如果(GetLastError()!=错误\u管道\u繁忙)
{
_tprintf(文本(“无法打开管道。GLE=%d\n”)、GetLastError();
返回-1;
}
//所有管道实例都很忙,请等待20秒。
如果(!WaitNamedPipe(lpszPipename,20000))
{
printf(“无法打开管道:20秒等待超时”);
返回-1;
}
}
//管道已连接;更改为消息读取模式。
dwMode=管道\读取模式\消息;
fSuccess=SetNamedPipeHandleState(
hPipe,//管道句柄
&dwMode,//新管道模式
NULL,//不设置最大字节数
NULL);//不设置最长时间
如果(!fsucces)
{
_tprintf(TEXT(“SetNamedPipeHandleState失败。GLE=%d\n”)、GetLastError();
返回-1;
}
//向管道服务器发送消息。
cbToWrite=(lstrlen(lpvMessage)+1)*sizeof(TCHAR);
_tprintf(文本(“发送%d字节消息:\%s\”\n”)、cbToWrite、lpvMessage;
fSuccess=WriteFile(
hPipe,//管道句柄
lpvMessage,//消息
cbToWrite,//消息长度
&cbwrited,//写入字节数
NULL);//不重叠
如果(!fsucces)
{
_tprintf(TEXT(“WriteFile to pipe failed.GLE=%d\n”)、GetLastError();
返回-1;
}
printf(“\n发送到服务器的消息,接收如下回复:\n”);
做
{
//从管子里读。
fSuccess=ReadFile(
hPipe,//管道句柄
chBuf,//接收应答的缓冲区
BUFSIZE*sizeof(TCHAR),//缓冲区大小
&cbRead,//读取的字节数
NULL);//不重叠
如果(!fsucces&&GetLastError()!=ERROR\u MORE\u DATA)
打破
_tprintf(文本(“\%s\”\n”),chBuf);
}while(!fsucces);//如果有更多数据出错,则重复循环
如果(!fsucces)
{
_tprintf(TEXT(“从管道读取文件失败。GLE=%d\n”)、GetLastError();
返回-1;
}
闭柄(hPipe);
返回0;
}
也许服务器应该尝试从循环中的管道中读取数据,直到达到您期望达到的所有数据为止(根据您与客户端的协议,例如,直到读取空终止符为止)。如果您打印出服务器接收到的缓冲区的.raw,您可以看到它实际上得到了整个消息:
> print repr(chBuf.raw)
'D\x00e\x00f\x00a\x00u\x00l\x00t\x00 \x00m\x00e\x00s\x00s\x00a\x00g\x00e\x00 \x00f\x00r\x00o\x00m\x00\x00c\x00l\x00i\x00e\x00n\x00t\x00.\x00\x00\x00\x00\x00 ... \x00\x00'
问题是合法字符之间有空值(\x00),当您试图打印chBuf.value时,这些值看起来像空终止符。那么为什么所有的零呢?这是因为C++客户端正在发送WCARGYT**消息(使用LPTSTR),但是Python服务器正在等待一个char字符串。
更改此行:
chBuf = create_string_buffer(BUFSIZE)
为此:
chBuf = create_unicode_buffer(BUFSIZE)
这应该可以解决问题
哦,还有,这里似乎有一个复制粘贴错误:
fSuccess = windll.kernel32.WriteFile(hPipe,c_char_pc_char_p(MESSAGE),len(MESSAGE),byref(cbWritten),None)
应该是:
fSuccess = windll.kernel32.WriteFile(hPipe, c_char_p(MESSAGE),len(MESSAGE),byref(cbWritten),None)
Python代码中有一个名称错误,直到我更改了它。只有在使用两种不同的语言运行时才会发生这种情况. 但是使用相同的语言,python和c++都在运行well@Varanka可能读取中的缓冲区不同。我仍然认为,在读取所有预期数据之前(或者达到EOF-管道已关闭),读取将更加正确。更具体地说,Windows TEXT()宏将生成ANSI或UTF-16字符串,具体取决于是否定义了UNICODE。看得好!因此,有一种方法可以在C++侧或Python端上修复代码: