使用JMS的简单聊天客户端

时间:2015-09-03 18:03:03

标签: swing java-ee netbeans jms chat

我使用Swing,Java Messaging Service和GlassFish4.1服务器从Jpanel构建一个聊天框,这样我就可以将它添加到我的Jframe应用程序中;但我似乎在建立连接时遇到了问题。

在运行期间,程序停在以下行:

TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup("BJconn");

我之前使用此客户端代码来处理企业应用程序,但现在我尝试将其添加到常规Java项目中,而不是卡住了。

真的很感激任何帮助,我对JMS很新,所以请尽量保持Lamen的答案。谢谢!

import java.awt.event.KeyEvent;
import javax.jms.*;
import javax.naming.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;

public class ChatPanel extends javax.swing.JPanel implements Runnable{

private Thread t = null;
private TopicConnection tpConnection = null;
private TopicPublisher tpPublisher = null;
private TopicSession tpSession = null;
private TopicSubscriber tpSubscriber = null;
private final String name;


/**
 * Creates new form chatFrame
 * @param nickName
 */
public ChatPanel(String nickName) 
{
  initComponents();
  DefaultCaret caret = (DefaultCaret) gameInfoTextArea.getCaret();
  caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
  name = nickName;
  connect();
}

/**
 * This method is called from within the constructor to initialise the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
// </editor-fold>                        

public JTextArea getTextArea()
{
  return gameInfoTextArea;
}        

public void setText(String textString)
{
  String s = gameInfoTextArea.getText() + "\n" + textString; 
  gameInfoTextArea.setText(s);
}        

private void connect()
{
 try
    {
      Context ctx = new InitialContext();
      TopicConnectionFactory tcf = (TopicConnectionFactory) 
              ctx.lookup("BJconn");
      tpConnection = tcf.createTopicConnection();
      tpConnection.setClientID(name);
      tpSession = tpConnection.createTopicSession(false, 
              TopicSession.AUTO_ACKNOWLEDGE);
      Topic topic = (Topic) ctx.lookup("BJDest");
      tpPublisher = tpSession.createPublisher(topic);
      tpSubscriber = tpSession.createDurableSubscriber(topic, name);
      tpConnection.start();
      t = new Thread(this);
      t.start();
    }
    catch (Exception e)
    {
       JOptionPane.showMessageDialog(null, "Chat cannot connect");
       System.out.println(e.getMessage());
    }
}        

/*private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    try 
    {
      tpConnection.close();
    }
    catch (Exception e)
    {
      JOptionPane.showMessageDialog(null, e.getMessage() );
    }        
} */                                                                                       



private void sendMessage()
{
  try
  {
    TextMessage tx = tpSession.createTextMessage();
    tx.setText(name + ": " + this.chatField.getText());
    tpPublisher.send(tx);
    this.chatField.setText("");
  }
  catch (Exception e)
  {
    JOptionPane.showMessageDialog(null, "Cannot send message");
  }    
}        

@Override
public void run()
{
  try
  {
    while (true)
    {
      TextMessage tx = (TextMessage) tpSubscriber.receive();
      if (tx != null)
      {
        String content = "";
        content += this.gameInfoTextArea.getText() + "\n" + tx.getText();
        this.gameInfoTextArea.setText(content);
        Thread.sleep(100);
      }    
    }    
  }
  catch (Exception e)
  {
    System.out.println(e.getMessage());
  }        
}        

/**
 * This method is called from within the constructor to initialise the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    chatField = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    gameInfoTextArea = new javax.swing.JTextArea();

    setBackground(new java.awt.Color(0, 102, 0));

    chatField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            chatFieldActionPerformed(evt);
        }
    });
    chatField.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyReleased(java.awt.event.KeyEvent evt) {
            chatFieldKeyReleased(evt);
        }
    });

    gameInfoTextArea.setEditable(false);
    gameInfoTextArea.setColumns(20);
    gameInfoTextArea.setRows(5);
    jScrollPane1.setViewportView(gameInfoTextArea);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(chatField)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(chatField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
}// </editor-fold>                        

private void chatFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
}                                         

private void chatFieldKeyReleased(java.awt.event.KeyEvent evt) {                                      
    if (evt.getKeyCode() == KeyEvent.VK_ENTER)
    {
      sendMessage();
    } 
}                                     


// Variables declaration - do not modify                     
private javax.swing.JTextField chatField;
private javax.swing.JTextArea gameInfoTextArea;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration                   

}

0 个答案:

没有答案