gpt4 book ai didi

c# - MSMQ c++ 到 c# 问题

转载 作者:行者123 更新时间:2023-11-30 03:07:28 26 4
gpt4 key购买 nike

我想使用 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,因为我不想使用任何消息格式化程序。

谢谢

最佳答案

我自己解决了这个问题。我会在这里发布代码,也许还有其他人感兴趣。

        try
{
Message received;
Stream bodyStream = null;
int bufLength = 512;
byte[] buffer = new byte[bufLength];

received = this.readMQ.Receive();
bodyStream = received.BodyStream;
bodyStream.Read(buffer, 0, bufLength);
this.lastReceived = Encoding.Unicode.GetString(buffer, 0, buffer.Length);

return lastReceived;
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString(), "Exception");
return null;
}

关于c# - MSMQ c++ 到 c# 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5816263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com