MINA实现的聊天软件

  1. 本文是转载的康康柳丁的文章,内容稍微做了修改,非常感谢程序的原作者,利用MINA
  2. 开发了这个示例程序,这是一个很好的通信模型,为开发一般的服务器程序提供了很好
  3. 的指导,但是程序中也存在很多的bug,我现在正在修改,相信过几天就会改好的,也希望
  4. 有更多的人能提供更多的有关MINA方面的资料和程序,MINA的确是一个不错的通信框架
  5. 希望大家能够多多的学习(文章末尾有原作者的博客链接)。
  6. 代码用到的包: mina-core-1.1.2.jar, swing-layout-1.0.jar ;slf4j-api-1.3.0.jar;slf4j-jdk14-1.3.0.jar。
  7. 工具类时间格式化;
  8. package chat.kanful;
  9. import java.text.ParseException;
  10. import java.text.SimpleDateFormat;
  11. import java.util.Calendar;
  12. import java.util.Date;
  13. /**
  14.  * 时期时间工具类
  15.  */
  16. public class DateTimeUtils {
  17.    private static Date date = new Date();
  18.    public final static SimpleDateFormat timeFormat = new SimpleDateFormat(
  19.          "HH:mm:ss");
  20.    public final static SimpleDateFormat dateFormat = new SimpleDateFormat(
  21.          "yyyy-MM-dd");
  22.    public final static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
  23.          "yyyy-MM-dd HH:mm:ss");
  24.    /**
  25.     * 
  26.     * 
  27.     * @return 明日是周几 星期一到七(1-7)
  28.     */
  29.    public static int getNextDayOfweek() {
  30.       Calendar calendar = Calendar.getInstance();
  31.       calendar.setTime(new java.util.Date(date.getTime() + 24 * 60 * 60
  32.             * 1000));
  33.       if (calendar.get(Calendar.DAY_OF_WEEK) == 1)
  34.          return 7;
  35.       else
  36.          return calendar.get(Calendar.DAY_OF_WEEK) - 1;
  37.    }
  38.    /**
  39.     * 
  40.     * 
  41.     * @return 明天的日期
  42.      * @throws ParseException
  43.     */
  44.    public static String getNextDay() {
  45.       String operationtime = dateFormat.format(new java.util.Date(date
  46.             .getTime()
  47.             + 24 * 60 * 60 * 1000));
  48.       return operationtime;
  49.    }
  50.    /**
  51.     * 
  52.     * 
  53.     * @return 今天的日期
  54.      */
  55.    public static String getToday() {
  56.       String operationtime = dateFormat.format(new java.util.Date(date
  57.             .getTime()));
  58.       return operationtime;
  59.    }
  60.    /**
  61.     * 
  62.     * @return 现在的时间 默认的系统格式
  63.      */
  64.    public static Date getNowTime() {
  65.       return new Date();
  66.    }
  67.    /**
  68.     * 
  69.     * @param date
  70.     * @return "yyyy-MM-dd" 格式的字符串
  71.      */
  72.    public static String validateDate(Date date) {
  73.       return date == null ? null : DateTimeUtils.dateFormat.format(date);
  74.    }
  75.    /**
  76.     * 
  77.     * @param date
  78.     * @return "HH:mm" 格式的字符串
  79.      */
  80.    public static String validateTime(Date date) {
  81.       return date == null ? null : DateTimeUtils.timeFormat.format(date);
  82.    }
  83.    /**
  84.     * 
  85.     * @param date
  86.     * @return "yyyy-MM-dd HH:mm:ss" 格式的字符串
  87.      */
  88.    public static String validateDateTime(Date date) {
  89.       return date == null ? null : DateTimeUtils.dateTimeFormat.format(date);
  90.    }
  91.    /**
  92.     * 
  93.     * @param dateStr
  94.     *           String 格式为"yyyy-MM-dd"
  95.     * @return 日期
  96.      */
  97.    public static Date validateDate(String dateStr) {
  98.       try {
  99.          return dateStr == null || dateStr.equals("") ? null
  100.                : DateTimeUtils.dateFormat.parse(dateStr);
  101.       } catch (ParseException e) {
  102.          e.printStackTrace();
  103.          return null;
  104.       }
  105.    }
  106.    /**
  107.     * 
  108.     * @param dateStr
  109.     *           String 格式为"HH:mm"
  110.     * @return 日期
  111.      */
  112.    public static Date validateTime(String dateStr) {
  113.       try {
  114.          return dateStr == null || dateStr.equals("") ? null
  115.                : DateTimeUtils.timeFormat.parse(dateStr);
  116.       } catch (ParseException e) {
  117.          e.printStackTrace();
  118.          return null;
  119.       }
  120.    }
  121.    /**
  122.     * 
  123.     * @param dateStr
  124.     *           String 格式为"yyyy-MM-dd HH:mm:ss"
  125.     * @return 日期
  126.      */
  127.    public static Date validateDateTime(String dateStr) {
  128.       try {
  129.          return dateStr == null || dateStr.equals("") ? null
  130.                : DateTimeUtils.dateTimeFormat.parse(dateStr);
  131.       } catch (ParseException e) {
  132.          e.printStackTrace();
  133.          return null;
  134.       }
  135.    }
  136. }
  137. 消息类:
  138. package chat.kanful;
  139. import java.io.Serializable;
  140. import java.util.List;
  141. /**
  142.  * 
  143.  * @author kanful
  144.  * 
  145.  */
  146. public class Message implements Serializable {
  147.    /**
  148.     * 
  149.     */
  150.    private static final long serialVersionUID = 8330482387552302479L;
  151.    private boolean login = false;
  152.    private boolean logout = false;
  153.    private String date;
  154.    private String content;
  155.    private String LoginName;
  156.    private List<String> reciverDeps;
  157.    public String getContent() {
  158.       return content;
  159.    }
  160.    public void setContent(String content) {
  161.       this.content = content;
  162.    }
  163.    public String getDate() {
  164.       return date;
  165.    }
  166.    public void setDate(String date) {
  167.       this.date = date;
  168.    }
  169.    public boolean isLogin() {
  170.       return login;
  171.    }
  172.    public void setLogin(boolean login) {
  173.       this.login = login;
  174.    }
  175.    public String getLoginName() {
  176.       return LoginName;
  177.    }
  178.    public void setLoginName(String loginName) {
  179.       LoginName = loginName;
  180.    }
  181.    public boolean isLogout() {
  182.       return logout;
  183.    }
  184.    public void setLogout(boolean logout) {
  185.       this.logout = logout;
  186.    }
  187.    public List<String> getReciverDeps() {
  188.       return reciverDeps;
  189.    }
  190.    public void setReciverDeps(List<String> reciverDeps) {
  191.       this.reciverDeps = reciverDeps;
  192.    }
  193.  }
  194. 服务端界面代码:
  195. /*
  196.  * ServerFrame.java
  197.  *
  198.  * Created on __DATE__, __TIME__
  199.  */
  200. package chat.kanful.server;
  201. import java.io.IOException;
  202. import javax.swing.JFrame;
  203. import javax.swing.JOptionPane;
  204. /**
  205.  * 
  206.  * @author __USER__
  207.  */
  208. public class ServerFrame extends javax.swing.JFrame {
  209.    /**
  210.     * 
  211.     */
  212.    private static final long serialVersionUID = -4765894664906136341L;
  213.    /** Creates new form ServerFrame */
  214.    public ServerFrame() {
  215.       initComponents();
  216.    }
  217.    /**
  218.     * This method is called from within the constructor to initialize the form.
  219.     * WARNING: Do NOT modify this code. The content of this method is always
  220.     * regenerated by the Form Editor.
  221.     */
  222.    // GEN-BEGIN:initComponents
  223.    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
  224.    private void initComponents() {
  225.       startButton = new javax.swing.JButton();
  226.       stopButton = new javax.swing.JButton();
  227.       jLabel1 = new javax.swing.JLabel();
  228.       portField = new javax.swing.JTextField();
  229.       setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  230.       startButton.setText("/u542f/u52a8");
  231.       startButton.addActionListener(new java.awt.event.ActionListener() {
  232.          public void actionPerformed(java.awt.event.ActionEvent evt) {
  233.             startHandler(evt);
  234.          }
  235.       });
  236.       stopButton.setText("/u505c/u6b62");
  237.       stopButton.setEnabled(false);
  238.       stopButton.addActionListener(new java.awt.event.ActionListener() {
  239.          public void actionPerformed(java.awt.event.ActionEvent evt) {
  240.             stopHandler(evt);
  241.          }
  242.       });
  243.       jLabel1.setText("/u7aef/u53e3/uff1a");
  244.       portField.setText("6016");
  245.       org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
  246.             getContentPane());
  247.       getContentPane().setLayout(layout);
  248.       layout
  249.             .setHorizontalGroup(layout
  250.                   .createParallelGroup(
  251.                         org.jdesktop.layout.GroupLayout.LEADING)
  252.                   .add(
  253.                         layout
  254.                               .createSequentialGroup()
  255.                               .addContainerGap(57, Short.MAX_VALUE)
  256.                               .add(
  257.                                     layout
  258.                                           .createParallelGroup(
  259.                                                 org.jdesktop.layout.GroupLayout.LEADING)
  260.                                           .add(
  261.                                                 layout
  262.                                                       .createSequentialGroup()
  263.                                                       .add(
  264.                                                             startButton)
  265.                                                       .addPreferredGap(
  266.                                                             org.jdesktop.layout.LayoutStyle.RELATED)
  267.                                                       .add(
  268.                                                             stopButton)
  269.                                                       .addContainerGap())
  270.                                           .add(
  271.                                                 org.jdesktop.layout.GroupLayout.TRAILING,
  272.                                                 layout
  273.                                                       .createSequentialGroup()
  274.                                                       .add(
  275.                                                             jLabel1)
  276.                                                       .addPreferredGap(
  277.                                                             org.jdesktop.layout.LayoutStyle.RELATED)
  278.                                                       .add(
  279.                                                             portField,
  280.                                                             org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  281.                                                             89,
  282.                                                             org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
  283.                                                       .add(
  284.                                                             75,
  285.                                                             75,
  286.                                                             75)))));
  287.       layout.setVerticalGroup(layout.createParallelGroup(
  288.             org.jdesktop.layout.GroupLayout.LEADING).add(
  289.             org.jdesktop.layout.GroupLayout.TRAILING,
  290.             layout.createSequentialGroup().addContainerGap(
  291.                   org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  292.                   Short.MAX_VALUE).add(
  293.                   layout.createParallelGroup(
  294.                         org.jdesktop.layout.GroupLayout.BASELINE).add(
  295.                         portField,
  296.                         org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  297.                         org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  298.                         org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
  299.                         .add(jLabel1)).add(20, 20, 20).add(
  300.                   layout.createParallelGroup(
  301.                         org.jdesktop.layout.GroupLayout.BASELINE).add(
  302.                         startButton).add(stopButton))
  303.                   .add(135, 135, 135)));
  304.       pack();
  305.    }// </editor-fold>//GEN-END:initComponents
  306.    JFrame serverFrame = this;
  307.    // GEN-FIRST:event_stopHandler
  308.    private void stopHandler(java.awt.event.ActionEvent evt) {
  309.       server.stop();
  310.       java.awt.EventQueue.invokeLater(new Runnable() {
  311.          public void run() {
  312.             startButton.setEnabled(true);
  313.             stopButton.setEnabled(false);
  314.          }
  315.       });
  316.    }// GEN-LAST:event_stopHandler
  317.    // GEN-FIRST:event_startHandler
  318.    private void startHandler(java.awt.event.ActionEvent evt) {
  319.       try {
  320.          server.start(Integer.parseInt(portField.getText()));
  321.       } catch (NumberFormatException e) {
  322.          JOptionPane.showMessageDialog(serverFrame, "请填写正确的端口""警告",
  323.                JOptionPane.WARNING_MESSAGE);
  324.          e.printStackTrace();
  325.       } catch (IOException e) {
  326.          JOptionPane.showMessageDialog(serverFrame, "连接失败""失败",
  327.                JOptionPane.INFORMATION_MESSAGE);
  328.          e.printStackTrace();
  329.       }
  330.       java.awt.EventQueue.invokeLater(new Runnable() {
  331.          public void run() {
  332.             startButton.setEnabled(false);
  333.             stopButton.setEnabled(true);
  334.          }
  335.       });
  336.    }// GEN-LAST:event_startHandler
  337.    // GEN-BEGIN:variables
  338.    // Variables declaration - do not modify
  339.    private javax.swing.JLabel jLabel1;
  340.    private javax.swing.JTextField portField;
  341.    private javax.swing.JButton startButton;
  342.    private javax.swing.JButton stopButton;
  343.    Server server = new Server();
  344.    /**
  345.     * @param args
  346.     *           the command line arguments
  347.     */
  348.    public static void main(String args[]) {
  349.       java.awt.EventQueue.invokeLater(new Runnable() {
  350.          public void run() {
  351.             ServerFrame serverFrame = new ServerFrame();
  352.             serverFrame.setLocation(400, 400);
  353.             serverFrame.setVisible(true);
  354.          }
  355.       });
  356.    }
  357.    // End of variables declaration//GEN-END:variables
  358. }
  359. Server类:
  360. package chat.kanful.server;
  361. import java.io.IOException;
  362. import java.net.InetSocketAddress;
  363. import org.apache.mina.common.DefaultIoFilterChainBuilder;
  364. import org.apache.mina.common.IoAcceptor;
  365. import org.apache.mina.common.IoAcceptorConfig;
  366. import org.apache.mina.common.ThreadModel;
  367. import org.apache.mina.filter.codec.ProtocolCodecFilter;
  368. import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
  369. import org.apache.mina.transport.socket.nio.SocketAcceptor;
  370. import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
  371. import org.slf4j.Logger;
  372. import org.slf4j.LoggerFactory;
  373. /**
  374.  * @author kanful
  375.  * 
  376.  */
  377. public class Server {
  378.    IoAcceptor acceptor;
  379.    IoAcceptorConfig config;
  380.    DefaultIoFilterChainBuilder chain;
  381.    private static Logger log = LoggerFactory.getLogger(Server.class);
  382.    public Server() {
  383.    }
  384.    public void start(int port) throws IOException {
  385.       acceptor = new SocketAcceptor();
  386.       config = new SocketAcceptorConfig();
  387.       chain = config.getFilterChain();
  388.       config.setThreadModel(ThreadModel.MANUAL);
  389.       // chain.addLast("logger", new LoggingFilter());
  390.       // chain.addLast("codec", new ProtocolCodecFilter(
  391.       // new TextLineCodecFactory(Charset.forName("UTF-8"))));
  392.       config.getFilterChain().addLast("codec",
  393.             new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
  394.       acceptor.bind(new InetSocketAddress(port), new ServerSessionHandler(),
  395.             config);
  396.       log.info("Listening on port " + port);
  397.    }
  398.    public void stop() {
  399.       try {
  400.          acceptor.unbindAll();
  401.          log.info("stop listening... ");
  402.          super.finalize();
  403.       } catch (Throwable e) {
  404.          e.printStackTrace();
  405.       }
  406.    } 
  407. }
  408. ServerHandler类:
  409. package chat.kanful.server;
  410. import java.util.ArrayList;
  411. import java.util.Date;
  412. import java.util.List;
  413. import java.util.concurrent.ConcurrentHashMap;
  414. import org.apache.mina.common.IdleStatus;
  415. import org.apache.mina.common.IoHandlerAdapter;
  416. import org.apache.mina.common.IoSession;
  417. import org.apache.mina.common.TransportType;
  418. import org.apache.mina.transport.socket.nio.SocketSessionConfig;
  419. import chat.kanful.Message;
  420. import chat.kanful.client.IOSessionException;
  421. /**
  422.  * @author kanful
  423.  * 
  424.  */
  425. public class ServerSessionHandler extends IoHandlerAdapter {
  426.    private ConcurrentHashMap<IoSession, String> customers = new ConcurrentHashMap<IoSession, String>();
  427.    public ServerSessionHandler() {
  428.       super();
  429.    }
  430.    public void sessionCreated(IoSession session) {
  431.       if (session.getTransportType() == TransportType.SOCKET)
  432.          ((SocketSessionConfig) session.getConfig())
  433.                .setReceiveBufferSize(2048);
  434.       session.setIdleTime(IdleStatus.BOTH_IDLE, 10);
  435.       List<String> list = new ArrayList<String>();
  436.       list.addAll(customers.values());
  437.       session.write(list);
  438.    }
  439.    public void exceptionCaught(IoSession session, Throwable cause) {
  440.       cause.printStackTrace();
  441.       customers.remove(session);
  442.       session.close();
  443.    }
  444.    public void messageReceived(IoSession session, Object msg) throws Exception {
  445.       if (!(msg instanceof Message)) {
  446.          throw new IOSessionException("格式错误");
  447.       }
  448.       Message message = (Message) msg;
  449.       if (message.isLogin()) {
  450.          String loginName = message.getLoginName();
  451.          if (customers.containsValue(loginName)) {
  452.             Message logoutMessage = new Message();
  453.             logoutMessage.setLogout(true);
  454.             session.write(logoutMessage);
  455.             System.out.println("接收一个新连接 有相同的用户名了。:");
  456.          } else {
  457.             System.out.println("接收一个新连:" + loginName);
  458.             createNewCustomer(session, loginName);
  459.          }
  460.       } else if (message.isLogout()) {
  461.          customers.remove(session);
  462.          session.close();
  463.       } else {
  464.          Date Datetime = DateTimeUtils.getNowTime();
  465.          message.setDate(DateTimeUtils.validateTime(Datetime));
  466.          message.setLoginName(customers.get(session));
  467.          notifyDeparments(message);
  468.       }
  469.    }
  470.    public void createNewCustomer(IoSession session, String department) {
  471.       customers.put(session, department);
  472.       List<String> list = new ArrayList<String>();
  473.       list.addAll(customers.values());
  474.       for (IoSession assesion : customers.keySet())
  475.          assesion.write(list);
  476.    }
  477.    public void notifyDeparments(Message message) {
  478.       List<String> depsList = message.getReciverDeps();
  479.       for (IoSession session : customers.keySet()) {
  480.          if (depsList.contains(customers.get(session))) {
  481.             session.write(message);
  482.          }
  483.       }
  484.    }
  485.    public void notifyAll(String message) {
  486.       for (IoSession session : this.customers.keySet()) {
  487.          session.write(message);
  488.       }
  489.    }
  490.    @Override
  491.    public void sessionClosed(IoSession session) throws Exception {
  492.       session = null;
  493.    }
  494.    public int getNumberOfUsers() {
  495.       return customers.size();
  496.    }
  497. }
  498. 客户端界面代码: 
  499. /*
  500.  * LogFrame.java
  501.  *
  502.  * Created on __DATE__, __TIME__
  503.  */
  504. package chat.kanful.client;
  505. import chat.kanful.Message;
  506. import java.awt.event.ActionEvent;
  507. import java.awt.event.ActionListener;
  508. import java.util.ArrayList;
  509. import java.util.List;
  510. import javax.swing.JFrame;
  511. import javax.swing.JOptionPane;
  512. import chat.kanful.DateTimeUtils;
  513. /**
  514.  * 
  515.  * @author __USER__
  516.  */
  517. public class LogFrame extends javax.swing.JFrame {
  518.    /**
  519.     * 
  520.     */
  521.    private static final long serialVersionUID = -1357955505013256203L;
  522.    // GEN-BEGIN:variables
  523.    // Variables declaration - do not modify
  524.    private javax.swing.JButton cancelButton;
  525.    private javax.swing.JLabel jLabel1;
  526.    private javax.swing.JLabel jLabel2;
  527.    private javax.swing.JScrollPane jScrollPane1;
  528.    private javax.swing.JScrollPane jScrollPane2;
  529.    private javax.swing.JButton loginButton;
  530.    private javax.swing.JTextArea msgArea;
  531.    private javax.swing.JTextField msgField;
  532.    private javax.swing.JTextField nameField;
  533.    private javax.swing.JList nameList;
  534.    private javax.swing.JButton sendButton;
  535.    // End of variables declaration//GEN-END:variables
  536.    private CustomerHandler handler;
  537.    private String name;
  538.    final int port = 6016;
  539.    private javax.swing.JFrame chatFrame;
  540.    /** Creates new form LogFrame */
  541.    public LogFrame() {
  542.       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  543.       initComponents();
  544.       handler = new CustomerHandler();
  545.       final JFrame jframe = this;
  546.       handler.setMessageListener(new MessageListener() {
  547.          public void onMessage(Message message) {
  548.             if (message.isLogout()) {
  549.                chatFrame.setVisible(false);
  550.                setVisible(true);
  551.                handler.disConnect();
  552.                JOptionPane.showMessageDialog(jframe, "有相同的用户名,请改换一个",
  553.                      "失败", JOptionPane.ERROR_MESSAGE);
  554.             }
  555.             msgArea.setText(msgArea.getText() + message.getDate() + "  "
  556.                   + message.getLoginName() + ":" + message.getContent()
  557.                   + "/n");
  558.          }
  559.          public void onNames(List list) {
  560.             System.out.println("接受新的用户列表");
  561.             list.remove(getName());
  562.             nameList.setListData(list.toArray());
  563.          }
  564.       });
  565.    }
  566.    // GEN-BEGIN:initComponents
  567.    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
  568.    private void initComponents() {
  569.       final javax.swing.JTextField urlField;
  570.       final LogFrame logFrame = this;
  571.       chatFrame = new javax.swing.JFrame();
  572.       jScrollPane1 = new javax.swing.JScrollPane();
  573.       msgArea = new javax.swing.JTextArea();
  574.       jScrollPane2 = new javax.swing.JScrollPane();
  575.       nameList = new javax.swing.JList();
  576.       msgField = new javax.swing.JTextField();
  577.       sendButton = new javax.swing.JButton();
  578.       jLabel1 = new javax.swing.JLabel();
  579.       nameField = new javax.swing.JTextField();
  580.       loginButton = new javax.swing.JButton();
  581.       cancelButton = new javax.swing.JButton();
  582.       jLabel2 = new javax.swing.JLabel();
  583.       urlField = new javax.swing.JTextField();
  584.       chatFrame.setSize(600, 500);
  585.       chatFrame.setVisible(false);
  586.       chatFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  587.       msgArea.setColumns(20);
  588.       msgArea.setRows(5);
  589.       jScrollPane1.setViewportView(msgArea);
  590.       jScrollPane2.setViewportView(nameList);
  591.       sendButton.setText("发送");
  592.       nameField.setText("用户名     ");
  593.       sendButton.addActionListener(new ActionListener() {
  594.          public void actionPerformed(ActionEvent e) {
  595.             Object[] sendNames = nameList.getSelectedValues();
  596.             List<String> names = new ArrayList<String>();
  597.             String sender = "";
  598.             for (Object str : sendNames) {
  599.                names.add((String) str);
  600.             }
  601.             if (names.isEmpty()) {
  602.                int leng = nameList.getLastVisibleIndex();
  603.                int[] indices = new int[leng + 1];
  604.                for (int i = 0; i <= leng; i++) {
  605.                   indices[i] = i;
  606.                }
  607.                nameList.setSelectedIndices(indices);
  608.                sendNames = nameList.getSelectedValues();
  609.                for (Object str : sendNames) {
  610.                   names.add((String) str);
  611.                }
  612.                sender = "所有人";
  613.             } else if (nameList.getMaxSelectionIndex() == names.size() - 1) {
  614.                sender = "所有人";
  615.             } else {
  616.                for (int i = 0; i < names.size(); i++) {
  617.                   sender += name;
  618.                   if (i != names.size() - 1) {
  619.                      sender += ",";
  620.                   }
  621.                }
  622.             }
  623.             Message msg = new Message();
  624.             msg.setReciverDeps(names);
  625.             msg.setContent(msgField.getText());
  626.             msgField.setText("");
  627.             try {
  628.                handler.sendMessage(msg);
  629.             } catch (IOSessionException e1) {
  630.                e1.printStackTrace();
  631.             }
  632.             StringBuffer msgBuffer = new StringBuffer();
  633.             msgBuffer.append(msgArea.getText());
  634.             msgBuffer.append(DateTimeUtils.validateTime(DateTimeUtils
  635.                   .getNowTime()));
  636.             msgBuffer.append("  ");
  637.             msgBuffer.append("我对 ");
  638.             msgBuffer.append(sender);
  639.             msgBuffer.append("说:");
  640.             msgBuffer.append(msg.getContent());
  641.             msgBuffer.append("/n");
  642.             msgArea.setText(msgBuffer.toString());
  643.          }
  644.       });
  645.       org.jdesktop.layout.GroupLayout jInternalFrame1Layout = new org.jdesktop.layout.GroupLayout(
  646.             chatFrame.getContentPane());
  647.       chatFrame.getContentPane().setLayout(jInternalFrame1Layout);
  648.       jInternalFrame1Layout
  649.             .setHorizontalGroup(jInternalFrame1Layout
  650.                   .createParallelGroup(
  651.                         org.jdesktop.layout.GroupLayout.LEADING)
  652.                   .add(
  653.                         jInternalFrame1Layout
  654.                               .createSequentialGroup()
  655.                               .add(
  656.                                     jScrollPane2,
  657.                                     org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  658.                                     58,
  659.                                     org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
  660.                               .addPreferredGap(
  661.                                     org.jdesktop.layout.LayoutStyle.RELATED)
  662.                               .add(
  663.                                     jInternalFrame1Layout
  664.                                           .createParallelGroup(
  665.                                                 org.jdesktop.layout.GroupLayout.LEADING,
  666.                                                 false)
  667.                                           .add(
  668.                                                 org.jdesktop.layout.GroupLayout.TRAILING,
  669.                                                 jInternalFrame1Layout
  670.                                                       .createSequentialGroup()
  671.                                                       .add(
  672.                                                             msgField)
  673.                                                       .addPreferredGap(
  674.                                                             org.jdesktop.layout.LayoutStyle.RELATED)
  675.                                                       .add(
  676.                                                             sendButton))
  677.                                           .add(
  678.                                                 jScrollPane1,
  679.                                                 org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  680.                                                 532,
  681.                                                 org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
  682.                               .add(33, 33, 33)));
  683.       jInternalFrame1Layout
  684.             .setVerticalGroup(jInternalFrame1Layout
  685.                   .createParallelGroup(
  686.                         org.jdesktop.layout.GroupLayout.LEADING)
  687.                   .add(
  688.                         jInternalFrame1Layout
  689.                               .createSequentialGroup()
  690.                               .addContainerGap()
  691.                               .add(
  692.                                     jInternalFrame1Layout
  693.                                           .createParallelGroup(
  694.                                                 org.jdesktop.layout.GroupLayout.LEADING)
  695.                                           .add(
  696.                                                 jInternalFrame1Layout
  697.                                                       .createSequentialGroup()
  698.                                                       .add(
  699.                                                             jScrollPane2,
  700.                                                             org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  701.                                                             332,
  702.                                                             Short.MAX_VALUE)
  703.                                                       .addContainerGap())
  704.                                           .add(
  705.                                                 org.jdesktop.layout.GroupLayout.TRAILING,
  706.                                                 jInternalFrame1Layout
  707.                                                       .createSequentialGroup()
  708.                                                       .add(
  709.                                                             jScrollPane1,
  710.                                                             org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  711.                                                             294,
  712.                                                             Short.MAX_VALUE)
  713.                                                       .addPreferredGap(
  714.                                                             org.jdesktop.layout.LayoutStyle.RELATED)
  715.                                                       .add(
  716.                                                             jInternalFrame1Layout
  717.                                                                   .createParallelGroup(
  718.                                                                         org.jdesktop.layout.GroupLayout.BASELINE)
  719.                                                                   .add(
  720.                                                                         sendButton)
  721.                                                                   .add(
  722.                                                                         msgField,
  723.                                                                         org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  724.                                                                         org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  725.                                                                         org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
  726.                                                       .add(
  727.                                                             19,
  728.                                                             19,
  729.                                                             19)))));
  730.       setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  731.       jLabel1.setText("/u767b/u5f55/u540d:");
  732.       loginButton.setText("/u767b/u5f55");
  733.       loginButton.addActionListener(new java.awt.event.ActionListener() {
  734.          public void actionPerformed(java.awt.event.ActionEvent evt) {
  735.             setName(nameField.getText());
  736.             handler.setLoginName(nameField.getText());
  737.             try {
  738.                handler.connect(urlField.getText(), port);
  739.             } catch (IOSessionException e) {
  740.                JOptionPane.showMessageDialog(logFrame, "连接失败,请重试""失败",
  741.                      JOptionPane.INFORMATION_MESSAGE);
  742.                e.printStackTrace();
  743.             }
  744.             java.awt.EventQueue.invokeLater(new Runnable() {
  745.                public void run() {
  746.                   msgArea.setText("连接成功!" + "/n");
  747.                   logFrame.setVisible(false);
  748.                   chatFrame.setSize(600, 300);
  749.                   chatFrame.setLocation(400, 400);
  750.                   chatFrame.setVisible(true);
  751.                }
  752.             });
  753.          }
  754.       });
  755.       cancelButton.addActionListener(new java.awt.event.ActionListener() {
  756.          public void actionPerformed(java.awt.event.ActionEvent evt) {
  757.             System.exit(0);
  758.          }
  759.       });
  760.       cancelButton.setText("/u53d6/u6d88");
  761.       jLabel2.setText("/u4e3b/u673a/u5730/u5740:");
  762.       urlField.setText("192.168.1.123");
  763.       org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
  764.             getContentPane());
  765.       getContentPane().setLayout(layout);
  766.       layout
  767.             .setHorizontalGroup(layout
  768.                   .createParallelGroup(
  769.                         org.jdesktop.layout.GroupLayout.LEADING)
  770.                   .add(
  771.                         layout
  772.                               .createSequentialGroup()
  773.                               .add(89, 89, 89)
  774.                               .add(
  775.                                     layout
  776.                                           .createParallelGroup(
  777.                                                 org.jdesktop.layout.GroupLayout.LEADING)
  778.                                           .add(
  779.                                                 layout
  780.                                                       .createSequentialGroup()
  781.                                                       .add(
  782.                                                             jLabel2)
  783.                                                       .addPreferredGap(
  784.                                                             org.jdesktop.layout.LayoutStyle.RELATED)
  785.                                                       .add(
  786.                                                             urlField,
  787.                                                             org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  788.                                                             org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  789.                                                             org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
  790.                                           .add(
  791.                                                 layout
  792.                                                       .createSequentialGroup()
  793.                                                       .add(
  794.                                                             layout
  795.                                                                   .createParallelGroup(
  796.                                                                         org.jdesktop.layout.GroupLayout.LEADING)
  797.                                                                   .add(
  798.                                                                         jLabel1)
  799.                                                                   .add(
  800.                                                                         loginButton))
  801.                                                       .add(
  802.                                                             2,
  803.                                                             2,
  804.                                                             2)
  805.                                                       .add(
  806.                                                             layout
  807.                                                                   .createParallelGroup(
  808.                                                                         org.jdesktop.layout.GroupLayout.LEADING)
  809.                                                                   .add(
  810.                                                                         layout
  811.                                                                               .createSequentialGroup()
  812.                                                                               .add(
  813.                                                                                     10,
  814.                                                                                     10,
  815.                                                                                     10)
  816.                                                                               .add(
  817.                                                                                     cancelButton))
  818.                                                                   .add(
  819.                                                                         nameField,
  820.                                                                         org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  821.                                                                         org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  822.                                                                         org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
  823.                               .addContainerGap(107, Short.MAX_VALUE)));
  824.       layout
  825.             .setVerticalGroup(layout
  826.                   .createParallelGroup(
  827.                         org.jdesktop.layout.GroupLayout.LEADING)
  828.                   .add(
  829.                         layout
  830.                               .createSequentialGroup()
  831.                               .add(38, 38, 38)
  832.                               .add(
  833.                                     layout
  834.                                           .createParallelGroup(
  835.                                                 org.jdesktop.layout.GroupLayout.BASELINE)
  836.                                           .add(jLabel2)
  837.                                           .add(
  838.                                                 urlField,
  839.                                                 org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  840.                                                 org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  841.                                                 org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
  842.                               .add(16, 16, 16)
  843.                               .add(
  844.                                     layout
  845.                                           .createParallelGroup(
  846.                                                 org.jdesktop.layout.GroupLayout.BASELINE)
  847.                                           .add(
  848.                                                 nameField,
  849.                                                 org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
  850.                                                 org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
  851.                                                 org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
  852.                                           .add(jLabel1))
  853.                               .add(15, 15, 15)
  854.                               .add(
  855.                                     layout
  856.                                           .createParallelGroup(
  857.                                                 org.jdesktop.layout.GroupLayout.BASELINE)
  858.                                           .add(loginButton).add(
  859.                                                 cancelButton))
  860.                               .addContainerGap(47, Short.MAX_VALUE)));
  861.       pack();
  862.    }// </editor-fold>//GEN-END:initComponents
  863.    // GEN-FIRST:event_jButton1ActionPerformed
  864.    // GEN-LAST:event_jButton1ActionPerformed
  865.    /**
  866.     * @param args
  867.     *           the command line arguments
  868.     */
  869.    public static void main(String args[]) {
  870.       java.awt.EventQueue.invokeLater(new Runnable() {
  871.          public void run() {
  872.             LogFrame logFrame = new LogFrame();
  873.             logFrame.setLocation(400, 400);
  874.             logFrame.setVisible(true);
  875.          }
  876.       });
  877.    }
  878.    public String getName() {
  879.       return name;
  880.    }
  881.    public void setName(String name) {
  882.       this.name = name;
  883.    }
  884. }
  885. 客户端handler 用户使用的门面类:
  886. package chat.kanful.client;
  887. import chat.kanful.Message;
  888. /**
  889.  * @author kanful
  890.  * 
  891.  */
  892. public class CustomerHandler {
  893.    private ClientSessionHandler clientHandler;
  894.    private Client client;
  895.    /**
  896.     * 
  897.     * @param deparment
  898.     */
  899.    public CustomerHandler() {
  900.       clientHandler = new ClientSessionHandler();
  901.    }
  902.    public CustomerHandler(String loginName, MessageListener messageListener) {
  903.       clientHandler = new ClientSessionHandler();
  904.       clientHandler.setLoginName(loginName);
  905.       clientHandler.setMessageListener(messageListener);
  906.    }
  907.    /**
  908.     * 
  909.     * @param department
  910.     */
  911.    public void setLoginName(String loginName) {
  912.       clientHandler.setLoginName(loginName);
  913.    }
  914.    /**
  915.     * 
  916.     * @param messageListener
  917.     */
  918.    public void setMessageListener(MessageListener messageListener) {
  919.       clientHandler.setMessageListener(messageListener);
  920.    }
  921.    /**
  922.     * 
  923.     * @param ip
  924.     * @param port
  925.     * @throws IOSessionException
  926.     */
  927.    public void connect(String ip, int port) throws IOSessionException {
  928.       if (clientHandler.getLoginName() == null) {
  929.          throw new IOSessionException("没有指定登录名");
  930.       }
  931.       client = new Client(ip, port, clientHandler);
  932.       client.start();
  933.    }
  934.    /**
  935.     */
  936.    public void disConnect() {
  937.       if (clientHandler.getSession() != null
  938.             && clientHandler.getSession().isConnected()) {
  939.          Message logoutMsg = new Message();
  940.          logoutMsg.setLogout(true);
  941.          clientHandler.getSession().write(logoutMsg);
  942.       }
  943.    }
  944.    /**
  945.     * 
  946.     * @param message
  947.     * @param departments
  948.     * @throws Exception
  949.     */
  950.    public void sendMessage(Message messgae) throws IOSessionException {
  951.       if (clientHandler.getSession() == null) {
  952.          throw new IOSessionException("连接已关闭!");
  953.       }
  954.       clientHandler.getSession().write(messgae);
  955.    }
  956. }
  957. client类:
  958. package chat.kanful.client;
  959. import java.net.InetSocketAddress;
  960. import org.apache.mina.filter.codec.ProtocolCodecFilter;
  961. import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
  962. import org.apache.mina.transport.socket.nio.SocketConnector;
  963. import org.apache.mina.transport.socket.nio.SocketConnectorConfig;
  964. /**
  965.  * @author kanful
  966.  * 
  967.  */
  968. public class Client {
  969.    private String ip;
  970.    private int port;
  971.    private int timeout = 30;
  972.    private SocketConnector connector;
  973.    private SocketConnectorConfig config;
  974.    private ClientSessionHandler clientHander;
  975.    protected Client(String ip, int port, ClientSessionHandler clientHander) {
  976.       this.ip = ip;
  977.       this.port = port;
  978.       this.clientHander = clientHander;
  979.    }
  980.    protected void start() {
  981.       connector = new SocketConnector();
  982.       config = new SocketConnectorConfig();
  983.       config.setConnectTimeout(timeout);
  984.       // config.getFilterChain().addLast("logger", new LoggingFilter());
  985.       // config.getFilterChain().addLast(
  986.       // "codec",
  987.       // new ProtocolCodecFilter(new TextLineCodecFactory(Charset
  988.       // .forName("UTF-8"))));
  989.       config.getFilterChain().addLast("codec",
  990.             new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
  991.       connector
  992.             .connect(new InetSocketAddress(ip, port), clientHander, config);
  993.    }
  994. }
  995. clientHandler:
  996. package chat.kanful.client;
  997. import java.util.List;
  998. import org.apache.mina.common.IoHandlerAdapter;
  999. import org.apache.mina.common.IoSession;
  1000. import chat.kanful.Message;
  1001. /**
  1002.  * @author kanful
  1003.  * 
  1004.  */
  1005. public class ClientSessionHandler extends IoHandlerAdapter {
  1006.    private IoSession session = null;
  1007.    private MessageListener messageListener;
  1008.    private String loginName;
  1009.    public ClientSessionHandler() {
  1010.    }
  1011.    public String getLoginName() {
  1012.       return loginName;
  1013.    }
  1014.    public void setLoginName(String loginName) {
  1015.       this.loginName = loginName;
  1016.    }
  1017.    public MessageListener getMessageListener() {
  1018.       return messageListener;
  1019.    }
  1020.    /**
  1021.     * 
  1022.     * @param messageListener
  1023.     */
  1024.    public void setMessageListener(MessageListener messageListener) {
  1025.       this.messageListener = messageListener;
  1026.    }
  1027.    public IoSession getSession() {
  1028.       return session;
  1029.    }
  1030.    public void setSession(IoSession session) {
  1031.       this.session = session;
  1032.    }
  1033.    @Override
  1034.    public void sessionClosed(IoSession arg0) throws Exception {
  1035.       if (session != null) {
  1036.          session = null;
  1037.       }
  1038.    }
  1039.    @Override
  1040.    public void sessionCreated(IoSession session) throws Exception {
  1041.       if (loginName == null || loginName.equals("")) {
  1042.          throw new IOSessionException("没有指字登录名");
  1043.       }
  1044.       Message loginMsg = new Message();
  1045.       loginMsg.setLogin(true);
  1046.       loginMsg.setLoginName(loginName);
  1047.       session.write(loginMsg);
  1048.       setSession(session);
  1049.    }
  1050.    public void messageReceived(IoSession session, Object msg) {
  1051.       if (msg instanceof String) {
  1052.       }
  1053.       if (msg instanceof List) {
  1054.          if (messageListener != null)
  1055.             messageListener.onNames((List) msg);
  1056.       } else if (msg instanceof Message) {
  1057.          Message message = (Message) msg;
  1058.          if (messageListener != null)
  1059.             messageListener.onMessage(message);
  1060.       }
  1061.    }
  1062.    public void exceptionCaught(IoSession session, Throwable cause) {
  1063.       if (session != null && session.isConnected()) {
  1064.          session.close();
  1065.       }
  1066.    }
  1067. }
  1068. 自定义异常类:
  1069. package chat.kanful.client;
  1070. public class IOSessionException extends Exception {
  1071.    private static final long serialVersionUID = 9095961801786998941L;
  1072.    public IOSessionException(String msg) {
  1073.       super(msg);
  1074.    }
  1075. }
  1076. 用来回调的接口。
  1077. package chat.kanful.client;
  1078. import chat.kanful.Message;
  1079. import java.util.List;
  1080. public interface MessageListener {
  1081.    public void onMessage(Message messge);
  1082.    public void onNames(List nameList);
  1083. }
  1084. (原文出自http://czhikang.blog.163.com/,本人对原文做了部分修改。)

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值