首页>代码>Java基于swing的学院管理系统>/EndDom/src/cn/com/cssve/chat/ServerFrame.java
/*
 * ServerFrame.java
 *
 * Created on __DATE__, __TIME__
 */

package cn.com.cssve.chat;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import cn.com.zh.entity.User;
import cn.com.zh.ui.MainFrame;
import cn.com.zh.util.TimeUtil;

/**
 *
 * @author  __USER__
 */
public class ServerFrame extends javax.swing.JFrame implements ActionListener,KeyListener {

	/** Creates new form ServerFrame */
	
	TimeUtil timeUtil = new TimeUtil();
	String time = TimeUtil.getTime();
	User p;
	public ServerFrame(final User user) {
		initComponents();
		setLocationRelativeTo(null);
		jButton4.addActionListener(this);
		createFile();
		this.setFocusable(true);
		this.addKeyListener(this);
		
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				setVisible(false);
			}
		});
	}
	
	private void createFile() {
		try {
			String newPath = System.getProperty("user.dir");
			dir = newPath + "\\记录\\" + time;
			fileDir = new File(dir);
			System.out.println(fileDir.getAbsolutePath());
			if (!fileDir.isDirectory()) {
				fileDir.mkdirs();
			}
			fileName = "聊天记录.txt";
			bw = new BufferedWriter(new FileWriter(dir + "\\" + fileName, true));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jButton_initiator = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList_user = new javax.swing.JList(new DefaultListModel<>());
jLabel_sate = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton_kick = new javax.swing.JButton();
jButton_send = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox();
jTextField_import = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("\u670d\u52a1\u5668");
setResizable(false);

jPanel1.setBackground(new java.awt.Color(204, 255, 204));

jButton_initiator.setFont(new java.awt.Font("楷体", 1, 18));
jButton_initiator.setText("\u542f\u52a8\u670d\u52a1\u5668");
jButton_initiator.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_initiatorActionPerformed(evt);
}
});

jList_user.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0), "\u7528\u6237\u5217\u8868", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("楷体", 1, 18)));
jList_user.setFont(new java.awt.Font("楷体", 0, 14));

jScrollPane1.setViewportView(jList_user);

jLabel_sate.setFont(new java.awt.Font("楷体", 1, 14));
jLabel_sate.setForeground(new java.awt.Color(255, 0, 51));
jLabel_sate.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel_sate.setText("\u5173\u95ed");
jLabel_sate.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "\u670d\u52a1\u5668\u72b6\u6001", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("楷体", 1, 24), new java.awt.Color(0, 204, 204)));

jTextArea1.setColumns(20);
jTextArea1.setEditable(false);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);

jButton_kick.setFont(new java.awt.Font("楷体", 1, 14));
jButton_kick.setText("\u8e22\u51fa\u7528\u6237");
jButton_kick.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_kickActionPerformed(evt);
}
});

jButton_send.setFont(new java.awt.Font("楷体", 1, 14));
jButton_send.setText("\u53d1 \u9001");
jButton_send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_sendActionPerformed(evt);
}
});

jButton3.setFont(new java.awt.Font("楷体", 1, 14));
jButton3.setText("\u6e05\u9664\u804a\u5929\u8bb0\u5f55");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

jButton4.setFont(new java.awt.Font("楷体", 1, 14));
jButton4.setText("\u4fdd\u5b58\u804a\u5929\u8bb0\u5f55");


jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "群      聊", "私      聊" }));

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton_initiator, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jButton_kick)
.addGap(18, 18, 18)))
.addGap(58, 58, 58)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton3)
.addGap(28, 28, 28)
.addComponent(jButton4)
.addGap(51, 51, 51))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField_import, javax.swing.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton_send)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton4))
.addGap(27, 27, 27))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_sate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jButton_initiator, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel_sate, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_send)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField_import, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jButton_kick))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3)
.addComponent(jButton4)
.addComponent(jButton4))))
.addGap(18, 18, 18))
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
);

pack();
}// </editor-fold>

	//GEN-END:initComponents
	//清空聊天记录
	private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
		int i = JOptionPane.showConfirmDialog(this, "你确定要清空聊天信息吗?", "提  示",
				JOptionPane.OK_CANCEL_OPTION);
		if (i == JOptionPane.OK_OPTION) {
			jTextArea1.setText("");
		} else {
			JOptionPane.showMessageDialog(null, "聊条信息清空失败!", "提  示",
					JOptionPane.INFORMATION_MESSAGE);
		}
	}

	//踢出用户
	protected void jButton_kickActionPerformed(ActionEvent evt) {
		Object object = jList_user.getSelectedValue();
		if (object != null) {
			ClientBean cb = (ClientBean) object;
			((DefaultListModel) jList_user.getModel()).removeElement(cb);
			try {
				cb.getSocket().close();
			} catch (IOException e) {
			} finally {
				String msg = "管理员将【" + cb.clientName + "】赶出聊天室";
				sendAll(msg);
				sendList();
			}
		} else {
			JOptionPane.showMessageDialog(null, "请从用户列表选择您要踢出的人");
		}

	}

	private void jButton_sendActionPerformed(ActionEvent evt) {
		String imp = jTextField_import.getText().trim();
		jTextField_import.setText("");
		if (imp.equals("")) {
			JOptionPane.showMessageDialog(null, "发送的信息不能为空");
		} else {
			//获得发送信息的类型
			int index = jComboBox1.getSelectedIndex();
			//索引0代表群聊
			if (index == 0) {
				String msg = "管理员对说有人说:" + imp;
				sendAll(msg);

			} else {
				Object obj = jList_user.getSelectedValue();
				if (obj == null) {
					JOptionPane.showMessageDialog(null, "私聊必须选择一个用户");
				} else {
					ClientBean cb = (ClientBean) obj;
					String msg = "管理员对【" + cb.getClientName() + "】说:" + imp;
					sendPrivate(msg, cb);
				}
			}
		}

	}

	// 启动服务器
	private void jButton_initiatorActionPerformed(java.awt.event.ActionEvent evt) {
		String text = jButton_initiator.getText();
		if (text.equals("启动服务器")) {
			startServer();
		} else {
			stopServer();
		}

	}

	public static int Post = 2002;
	public boolean flag = false;

	// 启动服务器
	private void startServer() {
		try {
			flag = true;
			socket = new ServerSocket(Post);
			jLabel_sate.setText("服务器正在监听" + Post + "端口");
			jButton_initiator.setText("关闭服务器");
			new ListenerThread().start();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "服务器启动失败!");
		}

	}

	//监听线程
	class ListenerThread extends Thread {
		@Override
		public void run() {
			while (flag) {
				try {
					Socket accp = socket.accept();
					//启动与客户端会话线程
					new chatThread(accp).start();
				} catch (IOException e) {
					flag = false;
				}

			}
		}
	}

	//客户端会话线程
	class chatThread extends Thread {
		private Socket s;

		public chatThread(Socket s) {
			this.s = s;
		}

		@Override
		public void run() {
			try {
				PrintWriter out = new PrintWriter(s.getOutputStream(), true);
				BufferedReader br = new BufferedReader(new InputStreamReader(
						s.getInputStream()));
				//获得客户端昵称
				String clientName = br.readLine();
				//			  System.out.println(clientName);
				if (existsClientName(clientName)) {
					s.close();
				} else {
					ClientBean cb = new ClientBean(s, clientName, out);
					DefaultListModel dlm = (DefaultListModel) jList_user
							.getModel();
					//将客户端添加到ServerControl界面
					dlm.addElement(cb);
					//欢迎词
					String welcome = "欢迎【" + clientName + "】来到【无聊】聊天室";
					//向各客户端发送欢迎词
					sendAll(welcome);
					//向客户端发送用户列表
					sendList();
					//启动获得客户端信息线程
					new GetThread(br, cb).start();
				}
			} catch (IOException e) {
			}
		}

		//获取客户端信息
		class GetThread extends Thread {
			private BufferedReader br;
			private ClientBean cb;

			public GetThread(BufferedReader br, ClientBean cb) {
				this.br = br;
				this.cb = cb;
			}

			@Override
			public void run() {
				try {
					while (true) {
						String text = br.readLine();
						String[] content = text.split(":");
						if (content[1].equals("all")) {
							String msg = content[0] + "对所有人说:" + content[2];
							sendAll(msg);
						} else {
							int index = Integer.parseInt(content[1]);
							Object object = jList_user.getModel().getElementAt(
									index);
							if (object != null) {
								ClientBean cb = (ClientBean) object;
								String msg = content[0] + "对"
										+ cb.getClientName() + "说" + content[2];
								sendPrivate(msg, cb);
							}
						}
					}
					//当客户端直接关闭窗台时,从JList中直接移除用户信息
				} catch (IOException e) {
					if (flag) {
						DefaultListModel dlm = (DefaultListModel) jList_user
								.getModel();
						//判断用户是否被管理员踢出来,若果不是就欢送
						if (dlm.contains(cb)) {
							dlm.removeElement(cb);
							String goodbye = "欢送【" + cb.getClientName()
									+ "】离开聊天室";
							sendAll(goodbye);
							sendList();
						}
					}

				}
			}
		}

		//点击发送按钮
		private void jButton_sendActionPerformed(java.awt.event.ActionEvent evt) {

			String imp = jTextField_import.getText().trim();
			jTextField_import.setText("");
			if (imp.equals("")) {
				JOptionPane.showMessageDialog(null, "发送的信息不能为空");
			} else {
				//获得发送信息的类型
				int index = jComboBox1.getSelectedIndex();
				//索引0代表群聊
				if (index == 0) {
					String msg = "管理员对说有人说:" + imp;
					sendAll(msg);
				} else {
					Object obj = jList_user.getValueIsAdjusting();
					if (obj == null) {
						JOptionPane.showMessageDialog(null, "私聊必须选择一个用户");
					} else {
						ClientBean cb = (ClientBean) obj;
						String msg = "管理员对" + cb.getClientName() + "说:" + imp;
						sendPrivate(msg, cb);
					}
				}
			}

		}

	}

	//发送群聊信息
	private void sendAll(String msg) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
		String getTime = sdf.format(new Date());
		jTextArea1.append(getTime+"\n"+msg + "\n");
		try {
			bw.write(msg+"\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Enumeration em = ((DefaultListModel) jList_user.getModel()).elements();
		if (em.hasMoreElements()) {
			ClientBean cb = (ClientBean) em.nextElement();
			cb.getPw().println(msg);
		}
	}

	//发送私有的信息
	public void sendPrivate(String text, ClientBean cb) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
		String getTime = sdf.format(new Date());
		jTextArea1.append(getTime+"\n"+text + "\n");
		try {
			bw.write(text);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cb.getPw().println(text);
	}

	private void sendList() {
		DefaultListModel dlm = (DefaultListModel) jList_user.getModel();
		Enumeration em = dlm.elements();
		if (em.hasMoreElements()) {
			ClientBean cb = (ClientBean) em.nextElement();
			cb.getPw().println("list:" + dlm.toString());
		}
	}

	//判断用户列表中是否含有相同的昵称
	public boolean existsClientName(String clientnName) {
		boolean flag = false;
		Enumeration emu = ((DefaultListModel) jList_user.getModel()).elements();
		while (emu.hasMoreElements()) {
			ClientBean cb = (ClientBean) emu.nextElement();
			if (cb.getClientName().equals(clientnName)) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	// 关闭服务器
	private void stopServer() {
		try {
			flag = false;
			jLabel_sate.setText("关   闭");
			jButton_initiator.setText("启动服务器");
			socket.close();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, "关闭服务器失败!");
		}

	}

//	public static void main(String args[]) {
//		java.awt.EventQueue.invokeLater(new Runnable() {
//			public void run() {
//				new ServerFrame().setVisible(true);
//			}
//		});
//	}

	private javax.swing.JButton jButton3;
	private javax.swing.JButton jButton4;
	private javax.swing.JButton jButton_initiator;
	private javax.swing.JButton jButton_kick;
	private javax.swing.JButton jButton_send;
	private javax.swing.JComboBox jComboBox1;
	private javax.swing.JLabel jLabel_sate;
	private javax.swing.JList jList_user;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JTextArea jTextArea1;
	private javax.swing.JTextField jTextField_import;
	// End of variables declaration//GEN-END:variables
	private ServerSocket socket;
	private BufferedWriter bw;
	private String fileName;
	private String dir;
	private File fileDir;

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==jButton4){
			try {
				int chose = JOptionPane.showConfirmDialog(null, "您需要保存聊天记录吗?",
						"提  示", JOptionPane.OK_CANCEL_OPTION);
				if (chose == JOptionPane.OK_OPTION) {
					bw.flush();//写入的过程
					JOptionPane.showMessageDialog(null, "聊天记录保存成功!");
				} else {
					
					
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode()==KeyEvent.VK_ESCAPE){
			
			int i = JOptionPane.showConfirmDialog(null, "是否退出?",
					"提  示", JOptionPane.YES_NO_OPTION);
			if(i==0){
				this.dispose();
				new MainFrame(p).setVisible(true);
			}
		}
		
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

}
最近下载更多
sunshine9920  LV12 2023年10月22日
rain112  LV31 2022年6月16日
testuser1234567  LV24 2022年5月31日
ming_123_9715  LV23 2022年5月3日
rodert  LV14 2022年4月29日
wangxin199804  LV9 2022年4月3日
wyx065747  LV67 2022年4月2日
978806986  LV16 2022年3月24日
543666826  LV33 2022年3月12日
qianzf  LV12 2021年12月22日
最近浏览更多
krispeng  LV13 9月17日
ZALZXB20030525 7月1日
暂无贡献等级
heshao  LV2 6月4日
hfffff  LV1 6月3日
MrDuan  LV2 5月15日
akittyboy  LV9 3月22日
jiayongchao258  LV9 2023年12月28日
磊哥哥哥哥  LV13 2023年12月26日
求学的熊猫  LV11 2023年12月25日
lshlsh 2023年12月25日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友