希望这个示例对您有所帮助。消息上有 BodyLength 属性,可用于确定正文长度。我在下面的示例中使用了相同的方法。你真的需要分配字节数组吗?如果您知道传入字节消息的格式,那么您可以简单地使用 IBytesMessage 类的不同 Read 方法来读取数据。例如使用 ReadInt 读取 Integer 数据,然后如果你有一个字节,然后调用 ReadByte 等。
void ReceiveMessages()
{
XMSFactoryFactory factoryFactory;
IConnectionFactory cf;
IConnection connectionWMQ;
ISession sessionWMQ;
IDestination destination;
IMessageConsumer consumer;
IBytesMessage bytesMessage;
// Get an instance of factory.
factoryFactory = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
// Create WMQ Connection Factory.
cf = factoryFactory.CreateConnectionFactory();
Console.WriteLine("Connection Factory created.");
// Set the properties
cf.SetStringProperty(XMSC.WMQ_HOST_NAME, "localhost");
cf.SetIntProperty(XMSC.WMQ_PORT, 1414);
cf.SetStringProperty(XMSC.WMQ_CHANNEL, "SVR_CHN");
cf.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);
cf.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, "MYQM");
cf.SetStringProperty(XMSC.USERID, "myuserId");
cf.SetStringProperty(XMSC.PASSWORD, "mypassw0rd");
// Create connection.
connectionWMQ = cf.CreateConnection();
Console.WriteLine("Connection created.");
// Create session
sessionWMQ = connectionWMQ.CreateSession(false, AcknowledgeMode.AutoAcknowledge);
Console.WriteLine("Session created.");
// Create destination
destination = sessionWMQ.CreateQueue("INBQ");
Console.WriteLine("Destination created.");
IMessageProducer prod = sessionWMQ.CreateProducer(destination);
IBytesMessage sendMsg = sessionWMQ.CreateBytesMessage();
sendMsg.WriteBytes(Encoding.ASCII.GetBytes("Hello world from WMQ"));
prod.Send(sendMsg);
// Create consumer
consumer = sessionWMQ.CreateConsumer(destination);
Console.WriteLine("Message Consumer created. Starting the connection now.");
// Start the connection to receive messages.
connectionWMQ.Start();
// Wait for 30 seconds for messages. Exit if no message by then
bytesMessage = (IBytesMessage)consumer.Receive(30000);
if (bytesMessage != null)
{
Console.WriteLine("Message received.");
byte[] uploadPayload = null;
uploadPayload = new byte[(int)bytesMessage.BodyLength];
bytesMessage.ReadBytes(uploadPayload);
Console.WriteLine(bytesMessage.BodyLength + "\n");
}
else
Console.WriteLine("Wait timed out.");
// Cleanup
consumer.Close();
destination.Dispose();
sessionWMQ.Dispose();
connectionWMQ.Close();
}