日期:2014-05-20 浏览次数:20920 次
this.field.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Socket socket = ClientFrame.this.client.getSocket();
if (socket != null && !socket.isClosed()) {
try {
//显示到本地消息框
ClientFrame.this.updateMessageFrame(
ClientFrame.this.client.getIdentityId(),
ClientFrame.this.client.getServerTime(),
ClientFrame.this.field.getText());
//发送给服务器,要求服务器转发这条信息
ClientFrame.this.client.execute(new Command(
CommandEnum.NORMAL_MESSAGE,
ClientFrame.this.client.getIdentityId())
.setParameter(CommandParameter.CONTENT, //CommandParameter.CONTENT是一个标识,用来存取消息的内容
ClientFrame.this.field.getText()));//取出输入框的内容
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
//为每个客户端开启一个线程监听 class CommandListenner implements Runnable { Socket socket = null; public CommandListenner(Socket s) { this.socket = s; } public void run() { while (Server.this.isServerStart() && this.socket != null && !this.socket.isClosed()) { Command cmd = null; try { cmd = Server.getRemoteCommand(this.socket); Server.this.commandHandler.execute(cmd, this.socket); } catch (IOException e) { e.printStackTrace(); return; } catch (ClassNotFoundException e) { e.printStackTrace(); return; } catch (Exception e) { if (this.socket == null || this.socket.isClosed()) { Server.this.disconnectClientSocket(socket); } else { e.printStackTrace(); } } } if (this.socket != null || !this.socket.isBound()) { Server.this.disconnectClientSocket(socket); } } }
/** * 发送消息 * from (消息发送者名称) * socket (接收者的) * date (时间) * content (消息内容) */ private boolean sendMessage(String from, Socket socket, long date, String content) { if (socket != null && socket.isConnected()) { // 问题所在区,如果将其注释掉,下面的语句将会导致循环发送数据 // 测试: System.out.println("发送给" + socket); return server.execute(new Command(CommandEnum.NORMAL_MESSAGE, from) .setParameter(CommandParameter.CONTENT, content) .setParameter(CommandParameter.IDENTITY_ID, from) .setParameter(CommandParameter.TIME, date), socket); } else { // 存入数据库 return true; } }
/** * 发送命令 * * @throws IOException */ public boolean execute(Command cmd) throws IOException { System.out.println("*"); ObjectOutputStream oos = null; if (this.socket != null && !this.socket.isClosed() && cmd != null) { oos = new ObjectOutputStream(this.socket.getOutputStream()); oos.writeObject(cmd); oos.flush(); if (cmd.getCmd() == CommandEnum.CLIENT_CLOSE) { this.isConnection = false; } return true; } return false; }