工具类时间格式化;
package chat.kanful;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 时期时间工具类
*
* @author kanful
*
*/
public class DateTimeUtils {
private static Date date = new Date();
public final static SimpleDateFormat timeFormat = new SimpleDateFormat(
"HH:mm:ss");
public final static SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
public final static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
/**
*
*
* @return 明日是周几 星期一到七(1-7)
*/
public static int getNextDayOfweek() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new java.util.Date(date.getTime() + 24 * 60 * 60
* 1000));
if (calendar.get(Calendar.DAY_OF_WEEK) == 1)
return 7;
else
return calendar.get(Calendar.DAY_OF_WEEK) - 1;
}
/**
*
*
* @return 明天的日期
* @throws ParseException
*/
public static String getNextDay() {
String operationtime = dateFormat.format(new java.util.Date(date
.getTime()
+ 24 * 60 * 60 * 1000));
return operationtime;
}
/**
*
*
* @return 今天的日期
*/
public static String getToday() {
String operationtime = dateFormat.format(new java.util.Date(date
.getTime()));
return operationtime;
}
/**
*
* @return 现在的时间 默认的系统格式
*/
public static Date getNowTime() {
return new Date();
}
/**
*
* @param date
* @return "yyyy-MM-dd" 格式的字符串
*/
public static String validateDate(Date date) {
return date == null ? null : DateTimeUtils.dateFormat.format(date);
}
/**
*
* @param date
* @return "HH:mm" 格式的字符串
*/
public static String validateTime(Date date) {
return date == null ? null : DateTimeUtils.timeFormat.format(date);
}
/**
*
* @param date
* @return "yyyy-MM-dd HH:mm:ss" 格式的字符串
*/
public static String validateDateTime(Date date) {
return date == null ? null : DateTimeUtils.dateTimeFormat.format(date);
}
/**
*
* @param dateStr
* String 格式为"yyyy-MM-dd"
* @return 日期
*/
public static Date validateDate(String dateStr) {
try {
return dateStr == null || dateStr.equals("") ? null
: DateTimeUtils.dateFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
*
* @param dateStr
* String 格式为"HH:mm"
* @return 日期
*/
public static Date validateTime(String dateStr) {
try {
return dateStr == null || dateStr.equals("") ? null
: DateTimeUtils.timeFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
*
* @param dateStr
* String 格式为"yyyy-MM-dd HH:mm:ss"
* @return 日期
*/
public static Date validateDateTime(String dateStr) {
try {
return dateStr == null || dateStr.equals("") ? null
: DateTimeUtils.dateTimeFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
消息类:
package chat.kanful;
import java.io.Serializable;
import java.util.List;
/**
*
* @author kanful
*
*/
public class Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8330482387552302479L;
private boolean login = false;
private boolean logout = false;
private String date;
private String content;
private String LoginName;
private List<String> reciverDeps;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public boolean isLogin() {
return login;
}
public void setLogin(boolean login) {
this.login = login;
}
public String getLoginName() {
return LoginName;
}
public void setLoginName(String loginName) {
LoginName = loginName;
}
public boolean isLogout() {
return logout;
}
public void setLogout(boolean logout) {
this.logout = logout;
}
public List<String> getReciverDeps() {
return reciverDeps;
}
public void setReciverDeps(List<String> reciverDeps) {
this.reciverDeps = reciverDeps;
}
}
服务端界面代码:
/*
* ServerFrame.java
*
* Created on __DATE__, __TIME__
*/
package chat.kanful.server;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author __USER__
*/
public class ServerFrame extends javax.swing.JFrame {
/**
*
*/
private static final long serialVersionUID = -4765894664906136341L;
/** Creates new form ServerFrame */
public ServerFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
startButton = new javax.swing.JButton();
stopButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
portField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
startButton.setText("/u542f/u52a8");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startHandler(evt);
}
});
stopButton.setText("/u505c/u6b62");
stopButton.setEnabled(false);
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopHandler(evt);
}
});
jLabel1.setText("/u7aef/u53e3/uff1a");
portField.setText("6016");
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout
.setHorizontalGroup(layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.addContainerGap(57, Short.MAX_VALUE)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(
startButton)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
stopButton)
.addContainerGap())
.add(
org.jdesktop.layout.GroupLayout.TRAILING,
layout
.createSequentialGroup()
.add(
jLabel1)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
portField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
89,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(
75,
75,
75)))));
layout.setVerticalGroup(layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING).add(
org.jdesktop.layout.GroupLayout.TRAILING,
layout.createSequentialGroup().addContainerGap(
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE).add(
layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE).add(
portField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel1)).add(20, 20, 20).add(
layout.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE).add(
startButton).add(stopButton))
.add(135, 135, 135)));
pack();
}// </editor-fold>//GEN-END:initComponents
JFrame serverFrame = this;
// GEN-FIRST:event_stopHandler
private void stopHandler(java.awt.event.ActionEvent evt) {
server.stop();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
startButton.setEnabled(true);
stopButton.setEnabled(false);
}
});
}// GEN-LAST:event_stopHandler
// GEN-FIRST:event_startHandler
private void startHandler(java.awt.event.ActionEvent evt) {
try {
server.start(Integer.parseInt(portField.getText()));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(serverFrame, "请填写正确的端口", "警告",
JOptionPane.WARNING_MESSAGE);
e.printStackTrace();
} catch (IOException e) {
JOptionPane.showMessageDialog(serverFrame, "连接失败", "失败",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
});
}// GEN-LAST:event_startHandler
// GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField portField;
private javax.swing.JButton startButton;
private javax.swing.JButton stopButton;
Server server = new Server();
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ServerFrame serverFrame = new ServerFrame();
serverFrame.setLocation(400, 400);
serverFrame.setVisible(true);
}
});
}
// End of variables declaration//GEN-END:variables
}
Server类:
package chat.kanful.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.IoAcceptorConfig;
import org.apache.mina.common.ThreadModel;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author kanful
*
*/
public class Server {
IoAcceptor acceptor;
IoAcceptorConfig config;
DefaultIoFilterChainBuilder chain;
private static Logger log = LoggerFactory.getLogger(Server.class);
public Server() {
}
public void start(int port) throws IOException {
acceptor = new SocketAcceptor();
config = new SocketAcceptorConfig();
chain = config.getFilterChain();
config.setThreadModel(ThreadModel.MANUAL);
// chain.addLast("logger", new LoggingFilter());
// chain.addLast("codec", new ProtocolCodecFilter(
// new TextLineCodecFactory(Charset.forName("UTF-8"))));
config.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
acceptor.bind(new InetSocketAddress(port), new ServerSessionHandler(),
config);
log.info("Listening on port " + port);
}
public void stop() {
try {
acceptor.unbindAll();
log.info("stop listening... ");
super.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
ServerHandler类:
package chat.kanful.server;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.TransportType;
import org.apache.mina.transport.socket.nio.SocketSessionConfig;
import chat.kanful.Message;
import chat.kanful.client.IOSessionException;
/**
* @author kanful
*
*/
public class ServerSessionHandler extends IoHandlerAdapter {
private ConcurrentHashMap<IoSession, String> customers = new ConcurrentHashMap<IoSession, String>();
public ServerSessionHandler() {
super();
}
public void sessionCreated(IoSession session) {
if (session.getTransportType() == TransportType.SOCKET)
((SocketSessionConfig) session.getConfig())
.setReceiveBufferSize(2048);
session.setIdleTime(IdleStatus.BOTH_IDLE, 10);
List<String> list = new ArrayList<String>();
list.addAll(customers.values());
session.write(list);
}
public void exceptionCaught(IoSession session, Throwable cause) {
cause.printStackTrace();
customers.remove(session);
session.close();
}
public void messageReceived(IoSession session, Object msg) throws Exception {
if (!(msg instanceof Message)) {
throw new IOSessionException("格式错误");
}
Message message = (Message) msg;
if (message.isLogin()) {
String loginName = message.getLoginName();
if (customers.containsValue(loginName)) {
Message logoutMessage = new Message();
logoutMessage.setLogout(true);
session.write(logoutMessage);
System.out.println("接收一个新连接 有相同的用户名了。:");
} else {
System.out.println("接收一个新连:" + loginName);
createNewCustomer(session, loginName);
}
} else if (message.isLogout()) {
customers.remove(session);
session.close();
} else {
Date Datetime = DateTimeUtils.getNowTime();
message.setDate(DateTimeUtils.validateTime(Datetime));
message.setLoginName(customers.get(session));
notifyDeparments(message);
}
}
public void createNewCustomer(IoSession session, String department) {
customers.put(session, department);
List<String> list = new ArrayList<String>();
list.addAll(customers.values());
for (IoSession assesion : customers.keySet())
assesion.write(list);
}
public void notifyDeparments(Message message) {
List<String> depsList = message.getReciverDeps();
for (IoSession session : customers.keySet()) {
if (depsList.contains(customers.get(session))) {
session.write(message);
}
}
}
public void notifyAll(String message) {
for (IoSession session : this.customers.keySet()) {
session.write(message);
}
}
@Override
public void sessionClosed(IoSession session) throws Exception {
session = null;
}
public int getNumberOfUsers() {
return customers.size();
}
}
客户端界面代码:
/*
* LogFrame.java
*
* Created on __DATE__, __TIME__
*/
package chat.kanful.client;
import chat.kanful.Message;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import chat.kanful.DateTimeUtils;
/**
*
* @author __USER__
*/
public class LogFrame extends javax.swing.JFrame {
/**
*
*/
private static final long serialVersionUID = -1357955505013256203L;
// GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton cancelButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton loginButton;
private javax.swing.JTextArea msgArea;
private javax.swing.JTextField msgField;
private javax.swing.JTextField nameField;
private javax.swing.JList nameList;
private javax.swing.JButton sendButton;
// End of variables declaration//GEN-END:variables
private CustomerHandler handler;
private String name;
final int port = 6016;
private javax.swing.JFrame chatFrame;
/** Creates new form LogFrame */
public LogFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
handler = new CustomerHandler();
final JFrame jframe = this;
handler.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
if (message.isLogout()) {
chatFrame.setVisible(false);
setVisible(true);
handler.disConnect();
JOptionPane.showMessageDialog(jframe, "有相同的用户名,请改换一个",
"失败", JOptionPane.ERROR_MESSAGE);
}
msgArea.setText(msgArea.getText() + message.getDate() + " "
+ message.getLoginName() + ":" + message.getContent()
+ "/n");
}
public void onNames(List list) {
System.out.println("接受新的用户列表");
list.remove(getName());
nameList.setListData(list.toArray());
}
});
}
// GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
final javax.swing.JTextField urlField;
final LogFrame logFrame = this;
chatFrame = new javax.swing.JFrame();
jScrollPane1 = new javax.swing.JScrollPane();
msgArea = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
nameList = new javax.swing.JList();
msgField = new javax.swing.JTextField();
sendButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
nameField = new javax.swing.JTextField();
loginButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
urlField = new javax.swing.JTextField();
chatFrame.setSize(600, 500);
chatFrame.setVisible(false);
chatFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
msgArea.setColumns(20);
msgArea.setRows(5);
jScrollPane1.setViewportView(msgArea);
jScrollPane2.setViewportView(nameList);
sendButton.setText("发送");
nameField.setText("用户名 ");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] sendNames = nameList.getSelectedValues();
List<String> names = new ArrayList<String>();
String sender = "";
for (Object str : sendNames) {
names.add((String) str);
}
if (names.isEmpty()) {
int leng = nameList.getLastVisibleIndex();
int[] indices = new int[leng + 1];
for (int i = 0; i <= leng; i++) {
indices[i] = i;
}
nameList.setSelectedIndices(indices);
sendNames = nameList.getSelectedValues();
for (Object str : sendNames) {
names.add((String) str);
}
sender = "所有人";
} else if (nameList.getMaxSelectionIndex() == names.size() - 1) {
sender = "所有人";
} else {
for (int i = 0; i < names.size(); i++) {
sender += name;
if (i != names.size() - 1) {
sender += ",";
}
}
}
Message msg = new Message();
msg.setReciverDeps(names);
msg.setContent(msgField.getText());
msgField.setText("");
try {
handler.sendMessage(msg);
} catch (IOSessionException e1) {
e1.printStackTrace();
}
StringBuffer msgBuffer = new StringBuffer();
msgBuffer.append(msgArea.getText());
msgBuffer.append(DateTimeUtils.validateTime(DateTimeUtils
.getNowTime()));
msgBuffer.append(" ");
msgBuffer.append("我对 ");
msgBuffer.append(sender);
msgBuffer.append("说:");
msgBuffer.append(msg.getContent());
msgBuffer.append("/n");
msgArea.setText(msgBuffer.toString());
}
});
org.jdesktop.layout.GroupLayout jInternalFrame1Layout = new org.jdesktop.layout.GroupLayout(
chatFrame.getContentPane());
chatFrame.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout
.setHorizontalGroup(jInternalFrame1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jInternalFrame1Layout
.createSequentialGroup()
.add(
jScrollPane2,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
58,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jInternalFrame1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING,
false)
.add(
org.jdesktop.layout.GroupLayout.TRAILING,
jInternalFrame1Layout
.createSequentialGroup()
.add(
msgField)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
sendButton))
.add(
jScrollPane1,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
532,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(33, 33, 33)));
jInternalFrame1Layout
.setVerticalGroup(jInternalFrame1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jInternalFrame1Layout
.createSequentialGroup()
.addContainerGap()
.add(
jInternalFrame1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jInternalFrame1Layout
.createSequentialGroup()
.add(
jScrollPane2,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
332,
Short.MAX_VALUE)
.addContainerGap())
.add(
org.jdesktop.layout.GroupLayout.TRAILING,
jInternalFrame1Layout
.createSequentialGroup()
.add(
jScrollPane1,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
294,
Short.MAX_VALUE)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
jInternalFrame1Layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(
sendButton)
.add(
msgField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(
19,
19,
19)))));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("/u767b/u5f55/u540d:");
loginButton.setText("/u767b/u5f55");
loginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
setName(nameField.getText());
handler.setLoginName(nameField.getText());
try {
handler.connect(urlField.getText(), port);
} catch (IOSessionException e) {
JOptionPane.showMessageDialog(logFrame, "连接失败,请重试", "失败",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
msgArea.setText("连接成功!" + "/n");
logFrame.setVisible(false);
chatFrame.setSize(600, 300);
chatFrame.setLocation(400, 400);
chatFrame.setVisible(true);
}
});
}
});
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
});
cancelButton.setText("/u53d6/u6d88");
jLabel2.setText("/u4e3b/u673a/u5730/u5740:");
urlField.setText("192.168.1.123");
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout
.setHorizontalGroup(layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(89, 89, 89)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(
jLabel2)
.addPreferredGap(
org.jdesktop.layout.LayoutStyle.RELATED)
.add(
urlField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(
layout
.createSequentialGroup()
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
jLabel1)
.add(
loginButton))
.add(
2,
2,
2)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(
10,
10,
10)
.add(
cancelButton))
.add(
nameField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(107, Short.MAX_VALUE)));
layout
.setVerticalGroup(layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.LEADING)
.add(
layout
.createSequentialGroup()
.add(38, 38, 38)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2)
.add(
urlField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(16, 16, 16)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(
nameField,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel1))
.add(15, 15, 15)
.add(
layout
.createParallelGroup(
org.jdesktop.layout.GroupLayout.BASELINE)
.add(loginButton).add(
cancelButton))
.addContainerGap(47, Short.MAX_VALUE)));
pack();
}// </editor-fold>//GEN-END:initComponents
// GEN-FIRST:event_jButton1ActionPerformed
// GEN-LAST:event_jButton1ActionPerformed
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
LogFrame logFrame = new LogFrame();
logFrame.setLocation(400, 400);
logFrame.setVisible(true);
}
});
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
客户端handler 用户使用的门面类:
package chat.kanful.client;
import chat.kanful.Message;
/**
* @author kanful
*
*/
public class CustomerHandler {
private ClientSessionHandler clientHandler;
private Client client;
/**
*
* @param deparment
*/
public CustomerHandler() {
clientHandler = new ClientSessionHandler();
}
public CustomerHandler(String loginName, MessageListener messageListener) {
clientHandler = new ClientSessionHandler();
clientHandler.setLoginName(loginName);
clientHandler.setMessageListener(messageListener);
}
/**
*
* @param department
*/
public void setLoginName(String loginName) {
clientHandler.setLoginName(loginName);
}
/**
*
* @param messageListener
*/
public void setMessageListener(MessageListener messageListener) {
clientHandler.setMessageListener(messageListener);
}
/**
*
* @param ip
* @param port
* @throws IOSessionException
*/
public void connect(String ip, int port) throws IOSessionException {
if (clientHandler.getLoginName() == null) {
throw new IOSessionException("没有指定登录名");
}
client = new Client(ip, port, clientHandler);
client.start();
}
/**
*/
public void disConnect() {
if (clientHandler.getSession() != null
&& clientHandler.getSession().isConnected()) {
Message logoutMsg = new Message();
logoutMsg.setLogout(true);
clientHandler.getSession().write(logoutMsg);
}
}
/**
*
* @param message
* @param departments
* @throws Exception
*/
public void sendMessage(Message messgae) throws IOSessionException {
if (clientHandler.getSession() == null) {
throw new IOSessionException("连接已关闭!");
}
clientHandler.getSession().write(messgae);
}
}
client类:
package chat.kanful.client;
import java.net.InetSocketAddress;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.SocketConnector;
import org.apache.mina.transport.socket.nio.SocketConnectorConfig;
/**
* @author kanful
*
*/
public class Client {
private String ip;
private int port;
private int timeout = 30;
private SocketConnector connector;
private SocketConnectorConfig config;
private ClientSessionHandler clientHander;
protected Client(String ip, int port, ClientSessionHandler clientHander) {
this.ip = ip;
this.port = port;
this.clientHander = clientHander;
}
protected void start() {
connector = new SocketConnector();
config = new SocketConnectorConfig();
config.setConnectTimeout(timeout);
// config.getFilterChain().addLast("logger", new LoggingFilter());
// config.getFilterChain().addLast(
// "codec",
// new ProtocolCodecFilter(new TextLineCodecFactory(Charset
// .forName("UTF-8"))));
config.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
connector
.connect(new InetSocketAddress(ip, port), clientHander, config);
}
}
clientHandler:
package chat.kanful.client;
import java.util.List;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import chat.kanful.Message;
/**
* @author kanful
*
*/
public class ClientSessionHandler extends IoHandlerAdapter {
private IoSession session = null;
private MessageListener messageListener;
private String loginName;
public ClientSessionHandler() {
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public MessageListener getMessageListener() {
return messageListener;
}
/**
*
* @param messageListener
*/
public void setMessageListener(MessageListener messageListener) {
this.messageListener = messageListener;
}
public IoSession getSession() {
return session;
}
public void setSession(IoSession session) {
this.session = session;
}
@Override
public void sessionClosed(IoSession arg0) throws Exception {
if (session != null) {
session = null;
}
}
@Override
public void sessionCreated(IoSession session) throws Exception {
if (loginName == null || loginName.equals("")) {
throw new IOSessionException("没有指字登录名");
}
Message loginMsg = new Message();
loginMsg.setLogin(true);
loginMsg.setLoginName(loginName);
session.write(loginMsg);
setSession(session);
}
public void messageReceived(IoSession session, Object msg) {
if (msg instanceof String) {
}
if (msg instanceof List) {
if (messageListener != null)
messageListener.onNames((List) msg);
} else if (msg instanceof Message) {
Message message = (Message) msg;
if (messageListener != null)
messageListener.onMessage(message);
}
}
public void exceptionCaught(IoSession session, Throwable cause) {
if (session != null && session.isConnected()) {
session.close();
}
}
}
自定义异常类:
package chat.kanful.client;
/**
* @author kanful
*
*/
public class IOSessionException extends Exception {
/**
*
*/
private static final long serialVersionUID = 9095961801786998941L;
public IOSessionException(String msg) {
super(msg);
}
}
用来回调的接口。
package chat.kanful.client;
import chat.kanful.Message;
import java.util.List;
/**
* @author kanful
*
*/
public interface MessageListener {
public void onMessage(Message messge);
public void onNames(List nameList);
}
代码用到的包: mina-core-1.1.2.jar, swing-layout-1.0.jar ;slf4j-api-1.3.0.jar;slf4j-jdk14-1.3.0.jar
问题,写了一年多j2ee,现在打包exe 都不会了,我把这两个都打成jar的,可以运行时老是老不到上面四个lib里的类,我用eclipse 把四个包也一起export导出了。就是找不到,应该怎么打包,用jsmooth工具打包成exe也不行,还是找不到lib里的东西。