Чат на ActiveMQ
От: Orgy243  
Дата: 15.12.15 11:58
Оценка:
]Здравствуйте, стоит задача реализовать приложение (чат), чтоб можно было сделать много копий запущенного приложения и вести переписку + чтоб копии могли определять сколько всего копий запущено.
Необходимо это реализовать с использованием AciveMQ.

Вид приложения как на скриншоте.

Собственно сам вопрос:
Как подключить и реализовать такой (чат) на ActiveMQ? Смотрел пример на сайте апача, понял что Producer надо повесить на кнопку "отправить" в моем примере это b, а для Consumer необходимо запихнуть в отдельный поток.

Клиент:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class Client {

    private static JTextArea ta;
    private static JTextField t;
    private static BufferedReader reader; //получает от сервера
    private static PrintWriter writer; // отправка на серва
    private static String Nic;
    
    
    public static void main(String[] args) {
        
        go();

    }

    private static void go() {
        
        Nic = JOptionPane.showInputDialog("Введите логин");
        
        JFrame f = new JFrame("Mess 1.0");
        
        f.setResizable(false); // окно не растянется
        f.setLocationRelativeTo(null); // в центре экрана 
        JPanel p = new JPanel();
        ta = new JTextArea(15, 30);
        ta.setLineWrap(true); //перенос строк
        ta.setWrapStyleWord(true); //перенос слов целиком, а не по слогам
        ta.setEditable(false);
        JScrollPane sp = new JScrollPane(ta);
        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        t = new JTextField(20);
        JButton b = new JButton ("Отправить");
        JButton re = new JButton ("Обновить");
        
        re.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                writer.print("");
            }
        });
        
        b.addActionListener(new Send()); // отправка
        
        
        
        
        p.add(sp);
        p.add(t);
        p.add(b);
        setNet();
        
        Thread thread = new Thread(new Listener());
        thread.start();
        
        f.getContentPane().add(BorderLayout.CENTER, p);
        f.getContentPane().add(BorderLayout.NORTH, re);
        f.setSize(400, 340);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }

    private static class Listener implements Runnable{

        @Override
        public void run() {
            String msg; 
            try{
                while((msg=reader.readLine())!=null){
                    ta.append(msg+"\n");
                }
            }catch(Exception ex){}
        }
        
    }  
    
    private static class Send implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            
            String msg = Nic+": "+t.getText();
            writer.println(msg); 
            writer.flush();
            
            t.setText("");
            t.requestFocus();
        }
    } 
    
    private static void setNet(){
        try {
            Socket sock = new Socket("127.0.0.1", 5000);
            InputStreamReader is = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(is);
            writer = new PrintWriter(sock.getOutputStream());
        } catch (Exception ex){}                 
    }
    
}


Пример HW апача:
import org.apache.activemq.ActiveMQConnectionFactory;
 
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
 
/**
 * Hello world!
 */
public class App {
 
    public static void main(String[] args) throws Exception {
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldConsumer(), false);
        Thread.sleep(1000);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldProducer(), false);
        Thread.sleep(1000);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldProducer(), false);
        Thread.sleep(1000);
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldProducer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldConsumer(), false);
        thread(new HelloWorldProducer(), false);
    }
 
    public static void thread(Runnable runnable, boolean daemon) {
        Thread brokerThread = new Thread(runnable);
        brokerThread.setDaemon(daemon);
        brokerThread.start();
    }
 
    public static class HelloWorldProducer implements Runnable {
        public void run() {
            try {
                // Create a ConnectionFactory
                ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
 
                // Create a Connection
                Connection connection = connectionFactory.createConnection();
                connection.start();
 
                // Create a Session
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
                // Create the destination (Topic or Queue)
                Destination destination = session.createQueue("TEST.FOO");
 
                // Create a MessageProducer from the Session to the Topic or Queue
                MessageProducer producer = session.createProducer(destination);
                producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
 
                // Create a messages
                String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode();
                TextMessage message = session.createTextMessage(text);
 
                // Tell the producer to send the message
                System.out.println("Sent message: "+ message.hashCode() + " : " + Thread.currentThread().getName());
                producer.send(message);
 
                // Clean up
                session.close();
                connection.close();
            }
            catch (Exception e) {
                System.out.println("Caught: " + e);
                e.printStackTrace();
            }
        }
    }
 
    public static class HelloWorldConsumer implements Runnable, ExceptionListener {
        public void run() {
            try {
 
                // Create a ConnectionFactory
                ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
 
                // Create a Connection
                Connection connection = connectionFactory.createConnection();
                connection.start();
 
                connection.setExceptionListener(this);
 
                // Create a Session
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
                // Create the destination (Topic or Queue)
                Destination destination = session.createQueue("TEST.FOO");
 
                // Create a MessageConsumer from the Session to the Topic or Queue
                MessageConsumer consumer = session.createConsumer(destination);
 
                // Wait for a message
                Message message = consumer.receive(1000);
 
                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    String text = textMessage.getText();
                    System.out.println("Received: " + text);
                } else {
                    System.out.println("Received: " + message);
                }
 
                consumer.close();
                session.close();
                connection.close();
            } catch (Exception e) {
                System.out.println("Caught: " + e);
                e.printStackTrace();
            }
        }
 
        public synchronized void onException(JMSException ex) {
            System.out.println("JMS Exception occured.  Shutting down client.");
        }
    }
}
java activemq jee
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.