【发布时间】:2011-08-14 13:09:09
【问题描述】:
我想使用 C++ 将消息写入 MSMQ 队列并使用 C# 读取它们。 我将消息作为字符串发送。 如果我在 C++ 中编写和读取消息,它工作正常,但如果我尝试使用 C# 读取消息,我只会得到消息的第一个字符。 (例如:我发送“abcd”,我只收到“a”)。
我还必须提到我在 Windows Mobile 中使用此代码。
这里是c++代码:
HRESULT MSMQManager::WriteMessage(LPWSTR text){
// define the required constants and variables.
const int NUMBEROFPROPERTIES = 5; // number of properties
DWORD cPropId = 0; // property counter
HRESULT hr = MQ_OK; // return code
HANDLE hQueue = NULL; // queue handle
// define an MQMSGPROPS structure.
MQMSGPROPS msgProps;
MSGPROPID aMsgPropId[NUMBEROFPROPERTIES];
MQPROPVARIANT aMsgPropVar[NUMBEROFPROPERTIES];
HRESULT aMsgStatus[NUMBEROFPROPERTIES];
// message label
aMsgPropId[cPropId] = PROPID_M_LABEL;
aMsgPropVar[cPropId].vt = VT_LPWSTR;
aMsgPropVar[cPropId].pwszVal = L"msg";
cPropId++;
// message body
aMsgPropId[cPropId] = PROPID_M_BODY;
aMsgPropVar[cPropId].vt = VT_VECTOR | VT_UI1;
aMsgPropVar[cPropId].caub.pElems = (LPBYTE)text;
aMsgPropVar[cPropId].caub.cElems = wcslen(text)*2;
cPropId++;
// message body type
aMsgPropId[cPropId] = PROPID_M_BODY_TYPE;
aMsgPropVar[cPropId].vt = VT_UI4;
aMsgPropVar[cPropId].ulVal = VT_LPWSTR;
cPropId++;
// initialize the MQMSGPROPS structure.
msgProps.cProp = cPropId;
msgProps.aPropID = aMsgPropId;
msgProps.aPropVar = aMsgPropVar;
msgProps.aStatus = aMsgStatus;
// Call MQSendMessage to send the message to the queue.
hr = MQSendMessage(
this->writeHandle, // Queue handle
&msgProps, // Message property structure
MQ_NO_TRANSACTION // Not in a transaction
);
这里是c#代码:
public string ReadMessageUnformatted()
{
try
{
Message received;
Stream bodyStream = null;
StreamReader sr = null;
char[] buffer = new char[256];
received = this.readMQ.Receive();
bodyStream = received.BodyStream;
sr = new StreamReader(bodyStream);
//this.lastReceived = sr.ReadLine();
sr.Read(buffer, 0, 256);
this.lastReceived = new string(buffer);
return lastReceived;
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString(), "Exception");
return null;
}
}
我使用 BodyStream 而不是 Body 作为消息,因为我不想使用任何消息格式化程序。
谢谢
【问题讨论】:
-
它是否适用于
string text = sr.ReadToEnd()? -
不,它也不适用于 ReadToEnd()。这样应用程序会阻塞等待流的结束。你认为这可能是一个问题,因为我将消息的正文设置为指针?
-
看看我的答案,也许在那儿。