⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatclient.java

📁 一个用Swing写的
💻 JAVA
字号:
/**
 * ClassName: ChatServer.java
 * Author: qiujy
 * CreateTime: 2008-7-28
 * EMAIL: qjyong@gmail.com
 * Copyright 2008 ++YONG All rights reserved.
 */
package com.bjjava.chat;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EtchedBorder;

import org.jvnet.substance.skin.SubstanceBusinessLookAndFeel;

/**
 * 客户端
 * @author qiujy
 */
public class ChatClient extends JFrame {
	private JTextArea chatTxt = new JTextArea();
	private JTextArea myWordTxt = new JTextArea();
	private JButton sendBtn = new JButton("发送(S)");
	private JButton closeBtn = new JButton("关闭(C)");
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	private String userName;
	private static int pid = 1;

	public ChatClient(String userName) {
		
		if(userName == null || userName.equals("")){
			this.userName = "游客" +( ++pid);
		}else{
			this.userName = userName;
		}
		this.init();
		
		// 连接服务器
		this.connect();
		
		//启动一个线程专门和服务器通信
		Thread thread = new Thread(new ChatClientRunner(socket, chatTxt));
		thread.start();

	}

	public void init() {
		this.setTitle("Swing聊天室");
		// 聊天记录面板
		JScrollPane listScroller = new JScrollPane(chatTxt,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		JPanel contentPanel = new JPanel();
		contentPanel.setLayout(new BorderLayout());
		contentPanel.add(listScroller);

		// 下部面板
		JScrollPane scrollPane = new JScrollPane(myWordTxt,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		// 要发送的内容面板
		JPanel myWordPanel = new JPanel();
		myWordPanel.setLayout(new BorderLayout());
		myWordPanel.add(scrollPane);
		// 按钮面板
		JPanel btnPanel = new JPanel();
		btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		btnPanel.add(new JLabel("我的昵称:" + this.userName + ""));
		btnPanel.add(closeBtn);
		btnPanel.add(sendBtn);
		myWordPanel.add(btnPanel, BorderLayout.SOUTH);

		// 分隔窗格
		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
				contentPanel, myWordPanel);
		splitPane.setDividerLocation(230);

		this.add(splitPane);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setResizable(false);
		this.setBounds(200, 200, 300, 400);

		this.setVisible(true);

		this.closeBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				closeConnect();
				System.exit(0);
			}
		});

		this.sendBtn.addActionListener(new SendAction());
	}

	private class SendAction implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			String temp = myWordTxt.getText();
			DateFormat formater = new SimpleDateFormat("HH:mm:ss");
			//System.out.println("c::" + temp);
			out.println(userName + " "+ formater.format(new Date()) + "说: " + temp);
			out.flush();
			myWordTxt.setText("");
		}
	}

	// 连接上服务器
	public void connect() {
		try {
			socket = new Socket("127.0.0.1", 8888);
			out = new PrintWriter(socket.getOutputStream());

		} catch (UnknownHostException e) {
			System.out.println("未连接上服务器!!!");
			System.exit(0);
			//e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 关闭连接
	public void closeConnect() {
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (in != null) {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

//与服务器进行通信的线程实现类
class ChatClientRunner implements Runnable {

	private Socket currentSocket;
	private JTextArea chatTxt;
	BufferedReader in;

	public ChatClientRunner(Socket currentSocket, JTextArea chatTxt) {
		this.currentSocket = currentSocket;
		this.chatTxt = chatTxt;
	}

	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(currentSocket
					.getInputStream()));
			while (true) {

				String text = in.readLine();
				if (text == null) {
					break;
				}
				chatTxt.append(text + "\n");
			}

		} catch (IOException e) {
			System.out.println("客户端主动关闭。。。。");
			//e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

// 登录框
class LoginFrame extends JFrame {
	private JTextField uNameTxt;
	private JTextField pwdTxt;
	private JButton loginBtn;
	private JButton resetBtn;
	private JLabel uNameMsg;

	public LoginFrame() {
		this.init();
	}

	public void init() {
		this.setTitle("聊天室用户登录");
		this.setBounds(300, 200, 330, 240);
		// logo
		Icon icon = new ImageIcon(this.getURL("logo.jpg"));
		JLabel logo = new JLabel(icon);
		this.add(logo, BorderLayout.NORTH);

		// main
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createTitledBorder(BorderFactory
				.createEtchedBorder(EtchedBorder.LOWERED), "用户登录"));
		this.add(panel);

		panel.setLayout(null);
		JLabel lbl = new JLabel("请输入昵称: ");
		lbl.setBounds(35, 35, 80, 25);
		panel.add(lbl);
		uNameTxt = new JTextField();
		uNameTxt.setBounds(120, 35, 120, 22);
		panel.add(uNameTxt);
		uNameMsg = new JLabel("");
		uNameMsg.setBounds(250, 35, 60, 25);
		panel.add(uNameMsg);

		JLabel lbl2 = new JLabel("请输入密码: ");
		lbl2.setBounds(35, 70, 80, 25);
		panel.add(lbl2);

		pwdTxt = new JPasswordField();
		pwdTxt.setBounds(120, 70, 120, 22);
		panel.add(pwdTxt);

		// btn
		JPanel btnPanel = new JPanel();
		btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 10));

		loginBtn = new JButton("登录(L)");
		loginBtn.addMouseListener(new LoginAction(this));

		resetBtn = new JButton("重置(R)");
		resetBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				uNameTxt.setText("");
				pwdTxt.setText("");
			}
		});

		btnPanel.add(resetBtn);
		btnPanel.add(loginBtn);
		this.add(btnPanel, BorderLayout.SOUTH);

		this.setVisible(true);
		this.setResizable(false);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	public class LoginAction extends MouseAdapter {
		private JFrame self;
		public LoginAction(JFrame self) {
			this.self = self;
		}

		@Override
		public void mouseClicked(MouseEvent e) {
			String uName = uNameTxt.getText();
			String pwd = pwdTxt.getText();
			// 创建出聊天面板
			new ChatClient(uName);
			uNameMsg.setText("");
			self.dispose();
		}

	}

	private URL getURL(String name) {
		return (Thread.currentThread().getContextClassLoader()
				.getResource(name));
	}
	
	public static void main(String[] args)throws UnsupportedLookAndFeelException {
		//===============更改感观=============================
		Font font = new Font("宋体", Font.PLAIN, 12);
		UIManager.put("Label.font", font);
		UIManager.put("Button.font", font);
		UIManager.setLookAndFeel(new SubstanceBusinessLookAndFeel());
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);

		new LoginFrame();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -