请帮助MQ nubee编写他的第一个Java客户端,我在Oracle文档中有点迷失。 我已经启动并运行OpenMQ。 在OpenMQ管理控制台中,我建立了一个名为“MyFirstTest”的代理 6个服务中的1个是“jms”(这似乎是最容易使用的服务),这个服务也启动并运行(说:服务状态正在运行)。 所以我来到了有趣的部分。 如何连接到代理“MyFirstTest”,然后发送消息,最后但最少可能从第二个客户端读取此消息。
我想我必须找到已经存在的队列而不是使用 新的com.sun.messaging.Queue
赞赏任何示例或链接。
public class HelloWorldMessage {
public static void main(String[] args) {
try {
ConnectionFactory myConnFactory;
Queue myQueue;
myConnFactory = new com.sun.messaging.ConnectionFactory();
Connection myConn = myConnFactory.createConnection();
Session mySess = myConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
myQueue = new com.sun.messaging.Queue("MyFirstTest");
//Create a message producer.
MessageProducer myMsgProducer = mySess.createProducer(myQueue);
//Create and send a message to the queue.
TextMessage myTextMsg = mySess.createTextMessage();
myTextMsg.setText("Hello World");
System.out.println("Sending Message: " + myTextMsg.getText());
myMsgProducer.send(myTextMsg);
//Create a message consumer.
MessageConsumer myMsgConsumer = mySess.createConsumer(myQueue);
//Start the Connection created in step 3.
myConn.start();
//Receive a message from the queue.
Message msg = myMsgConsumer.receive();
//Retreive the contents of the message.
if (msg instanceof TextMessage) {
TextMessage txtMsg = (TextMessage) msg;
System.out.println("Read Message: " + txtMsg.getText());
}
//Close the session and connection resources.
mySess.close();
myConn.close();
} catch (Exception jmse) {
System.out.println("Exception occurred : " + jmse.toString());
jmse.printStackTrace();
}
}
}
答案 0 :(得分:1)
//Assuming server supports multiple clients, your client can look like this:
//Ref: http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
//untested code
class client{
.....
....
private static Socket echoSocket;
//main can be in another class also
public static void main(.... args[]){
client nodeI,nodeII;
nodeI = new client("speaker/sender");
nodeII = new client("listener/recvr");
nodeI.connect2Server();
nodeI.sendMssgInstr2Server(node);
}
public void connect2Server(){
try {
echoSocket = new Socket("<jms.srvr.ip>", <port#>);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: <jms.srvr.ip>.");
System.exit(1);
}
}
public void sendMssgInstr2Server throws IOException (client RecipientClientNodeII){
out = new PrintWriter(echoSocket.getOutputStream(), true);
out.println("sending message:"+mssgQueue.poll() + " =>recipient client is now reading:"+RecipientClientNodeII.receive);
}
public void receive(){
try{
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}catch (IOException e) {
System.err.println("Couldn't get I/O for "+"the connection to: <jms.srvr.ip>.");
System.exit(1);
}
while(1)
in.readLine();
}
//other methods
.......
.......
}; //class client ends