0

这是服务器的代码:

import java.net.UnknownHostException;
import java.io.IOException;
import org.apache.activemq.transport.stomp.StompConnection;
public class Server{

public static void main(String[] args) {
    try {
        StompConnection con = new StompConnection();
        con.open("localhost", 61618);
        con.connect("admin", "admin123");
        con.begin("a1");
        con.send("/queue/test1", "This is test message 1");
        con.send("/queue/test1", "This is test message 2");
        con.send("/queue/test1", "This is test message 3");
        con.commit("a1");
        con.disconnect();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

这是客户端的代码:

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Scanner;
import org.apache.activemq.transport.stomp.StompConnection;
import org.apache.activemq.transport.stomp.StompFrame;
import org.apache.activemq.transport.stomp.Stomp.Headers.Subscribe;

public class Client {

public static void main(String[] args) {
    try {
        //login.
        Scanner in = new Scanner(System.in);
        System.out.print("Password: ");
        String pass = in.next();
        if (!"123".equals(pass)){
            System.out.println("Sorry, wrong password.");

        }
        else
        {
            StompConnection con= new StompConnection();
            con.open("localhost", 61618);
            con.connect("admin", "admin123");
            con.subscribe("/queue/test1", Subscribe.AckModeValues.CLIENT);
            con.begin("a2");
            StompFrame mes = con.receive();
            System.out.println(mes.getBody());
            con.ack(message, "a2");
            con.commit("a2");               
            con.disconnect();
        }


    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

我在服务器上有 3 条消息。但是,我每次只能在 Client 中收到 1 条消息。如何在运行中获取队列中的所有消息?任何人都可以帮助我吗?

4

1 回答 1

0

不完全确定您在这里尝试了什么,但阅读所有三个只是一个简单的循环,例如:

    con.begin("a2");
    while (true) {
        StompFrame message = null;
        try {
            message = connection.receive(5000);
        } catch (Exception e) {
            break;
        }
        System.out.println(mes.getBody());
        con.ack(message, "a2");
    }
    connection.commit("a2");                
于 2013-04-03T14:48:27.407 回答