教育路上

全国站>Java>网络编程>java聊天室综合案例
发布需求
填写需求信息关闭
我们会根据您的需求匹配

姓      名:

意向城市:

留      言:

手机号码:

验  证  码:  换一张

确认提交

java聊天室综合案例

摘要:java综合案例,java 综合 案例。以下是我们为大家整理的,相信大家阅读完后肯定有了自己的选择吧。

2022-07-02 16:25网络推荐

发布时间:
2022-07-02 16:25
信息来源:
网络推荐
浏览次数:
853
java聊天室综合案例

from shengerguan from shengerguan


代码下载 

客户端


package aw;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import java.io.InputStream;
import java.io.OutputStream;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

class cilentthread implements Runnable {
	private Socket socket;
	private JComboBox comboBox = new JComboBox();
	private JTextArea chatContent = new JTextArea(12, 34);

	cilentthread(Socket socket, JComboBox comboBox, JTextArea chatContent) {
		this.socket = socket;
		this.comboBox = comboBox;
		this.chatContent = chatContent;
	}

	public void run() {
		try {
			while (true) {
				InputStream in = socket.getInputStream();
				byte[] buf = new byte[1024];
				int len = in.read(buf);
				String instr = new String(buf, 0, len);
				String[] str = instr.split("@");
				
				switch (str[0]) {
				case "list":
					for (String user : str) {
						if (!user.equals("list"))
							comboBox.addItem(user);
					}
					break;
				case "welcome":
					chatContent.append(str[1] + "\n");
					break;
				case "all":
					chatContent.append(str[1] + "\n");
					break;
				case "private":
					chatContent.append(str[1] + "\n");
					break;
				}
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}
}

public class reguser extends JFrame {
	// 用到的组件,定义成员变量,全局可用
	JButton add, reg, login;
	JComboBox comboBox = new JComboBox();
	JTextArea chatContent = new JTextArea(12, 34);
	String senduser;
	Socket socket;
	ResultSet rs = null;
	Statement stmt = null;
	Connection conn = null;

	void gui() {// 图形界面
		JFrame f = new JFrame("综合案例");
		f.setSize(300, 200);
		f.setLocation(300, 200);

		reg = new JButton("注册");
		login = new JButton("登录");
		f.setLayout(new FlowLayout());
		f.add(reg);
		f.add(login);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);

		reg.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				reg();
			}
		});

		login.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				login();
			}
		});

	}

	void conn() {// 建立数据库连接
		try {
			// 1. 注册数据库的驱动
			Class.forName("com.mysql.jdbc.Driver");
			// 2.通过DriverManager获取数据库连接
			String url = "jdbc:mysql://localhost:3306/mysql";
			String username = "root";
			String password = "";
			conn = (Connection) DriverManager.getConnection(url, username, password);
			// 3.通过Connection对象获取Statement对象
			stmt = (Statement) conn.createStatement();
			// 4.使用Statement执行SQL语句。
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void connclose() {// 数据库的关闭
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null;
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			stmt = null;
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
		}
	}

	void showmsg(String str) {
		JDialog dialog = new JDialog(reguser.this, true);
		dialog.setTitle("提示信息");
		dialog.setSize(300, 200);
		dialog.setLocation(50, 50);
		JLabel j = new JLabel(str);
		dialog.add(j);
		dialog.setVisible(true);
	}

	void reg() {// 注册账号
		JDialog dialog = new JDialog(reguser.this, true);
		dialog.setTitle("用户注册");
		dialog.setSize(300, 200);
		dialog.setLocation(50, 50);
		JLabel j = new JLabel("用户名:");
		JLabel m = new JLabel("密码:");
		JTextField u = new JTextField(20);
		JTextField p = new JTextField(20);
		JButton regsave = new JButton("提交");
		dialog.setLayout(new GridLayout(3, 3));
		dialog.add(j);
		dialog.add(u);
		dialog.add(m);
		dialog.add(p);
		dialog.add(regsave);

		regsave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String a = u.getText();
				String b = p.getText();
				conn();
				try {
					stmt.executeUpdate("use user"); // 使company成为当前数据库
					// 检查用户名重复
					rs = stmt.executeQuery("select id from user where user='" + a + "'");
					if (rs.next()) {
						showmsg("用户名已经存在!失败");
						return;
					}
					// 自动增加id
					rs = stmt.executeQuery("select max(id) as num from user");
					int i;
					if (rs.next()) {
						i = rs.getInt("num") + 1;
					} else {
						i = 1;
					}
					stmt.executeUpdate("insert into user values(" + i + ",'" + a + "','" + b + "')");
					showmsg("注册成功");
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});

		dialog.setVisible(true);

	}

	void login() {// 登录账号
		JDialog dialog = new JDialog(reguser.this, true);
		dialog.setTitle("用户登录");
		dialog.setSize(300, 200);
		dialog.setLocation(50, 50);
		JLabel j = new JLabel("用户名:");
		JLabel m = new JLabel("密码:");
		JTextField u = new JTextField(20);
		JTextField p = new JTextField(20);
		JButton s = new JButton("登录");
		dialog.setLayout(new GridLayout(3, 3));
		dialog.add(j);
		dialog.add(u);
		dialog.add(m);
		dialog.add(p);
		dialog.add(s);

		s.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String a = u.getText();
				String b = p.getText();
				conn();
				try {
					stmt.executeUpdate("use user"); // 使company成为当前数据库
					// 检查用户名重复
					rs = stmt.executeQuery("select id from user where user='" + a + "' and pass='" + b + "'");
					if (rs.next()) {
						senduser = a;
						server();
						chatgui();
						return;
					} else {
						showmsg("登录失败!");
						return;
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});

		dialog.setVisible(true);
	}

	void chatgui() {
		JDialog dialog = new JDialog(reguser.this, true);
		dialog.setTitle("聊天室");
		dialog.setSize(800, 500);
		dialog.setLocation(50, 50);
		dialog.setLayout(new BorderLayout());
		JScrollPane showPanel = new JScrollPane(chatContent);
		chatContent.setEditable(false);
		JPanel inputPanel = new JPanel();
		JTextField inputField = new JTextField(20);
		JButton sendBt = new JButton("发送");
		// 为按钮添加事件
		sendBt.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String content = inputField.getText();
				if (content != null && !content.trim().equals("")) {
					String item = (String) comboBox.getSelectedItem();
					try {
						if (item.equals("所有人")) {
							OutputStream out = socket.getOutputStream();
							String str = "all@" + senduser + "@" + content;
							out.write(str.getBytes());
						} else {
							OutputStream out = socket.getOutputStream();
							String str = "private@" + senduser + "@" + item + "@" + content;
							out.write(str.getBytes());
						}
					} catch (IOException e1) {
						// TODO 自动生成的 catch 块
						e1.printStackTrace();
					}
				} else {
					chatContent.append("聊天信息不能为空" + "\n");
				}
				inputField.setText("");
			}
		});
		comboBox.addItem("所有人");
		inputPanel.add(comboBox);
		inputPanel.add(inputField);
		inputPanel.add(sendBt);
		dialog.add(showPanel, BorderLayout.CENTER);
		dialog.add(inputPanel, BorderLayout.SOUTH);
		dialog.setVisible(true);

	}

	void server() {
		try {
			socket = new Socket("127.0.0.1", 10001);
			new Thread(new cilentthread(socket, comboBox, chatContent)).start();
			OutputStream out = socket.getOutputStream();
			String str = "welcome@" + senduser;
			out.write(str.getBytes());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] aa) {
		reguser u = new reguser();
		u.gui();

	}
}

服务端

package aw;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

class serverthread implements Runnable {
	private Socket socket;
	private HashMap<String, Socket> userList = new HashMap<String, Socket>();;

	serverthread(Socket socket, HashMap<String, Socket> userList) {
		this.socket = socket;
		this.userList = userList;
	}

	public void run() {
		
		try {
			while (true) {
				InputStream in = socket.getInputStream();
				byte[] buf = new byte[1024];
				int len = in.read(buf);
				String instr = new String(buf, 0, len);
				String[] str = instr.split("@");
				Set<String> users;
				String outstr;
				switch (str[0]) {
				case "welcome":
					userList.put(str[1], socket);
					users = userList.keySet();
					Object[] names = users.toArray();
					StringBuilder sb = new StringBuilder();
					for (Object name : names)
						sb.append("@" + (String) name);
					outstr = "list" + sb.toString();
					
					for (String user : users) {
						Socket so = userList.get(user);
						try {
							OutputStream out = so.getOutputStream();
							out.write(outstr.getBytes());
							System.out.print(outstr);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

					for (String user : users) {
						Socket so = userList.get(user);
						try {
							outstr = "welcome@欢迎:" + str[1] + "进入聊天室!";
							OutputStream out = so.getOutputStream();
							out.write(outstr.getBytes());
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					break;
				case "all":
					users = userList.keySet();
					for (String user : users) {
						Socket so = userList.get(user);
						try {
							outstr = "all@" + str[1] + "对所有人说:" + str[2];
							OutputStream out = so.getOutputStream();
							out.write(outstr.getBytes());
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					break;
				case "private":
					Socket so = userList.get(str[2]);
					outstr = "private@" + str[1] + "对" + str[2] + "说:" + str[3];
					OutputStream out = so.getOutputStream();
					out.write(outstr.getBytes());
					break;
				}
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}

public class sever {

	public static void main(String[] args) {
		HashMap<String, Socket> userList = new HashMap<String, Socket>();
		Socket client;
		JFrame f = new JFrame("服务端");
		f.setSize(300, 200);
		f.setLocation(300, 200);
		f.setLayout(new FlowLayout());
		JLabel j = new JLabel("服务端已启动");
		f.add(j);
		JButton add = new JButton("创建");
		f.add(add);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);

		// 数据库创建
		add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				add();
			}

			private void add() {
				reguser u = new reguser();

				u.conn();
				try {

					String sql = "select TABLE_NAME from information_schema.TABLES where table_schema ='user' and table_name = 'user'";
					u.rs = u.stmt.executeQuery(sql);
					if (u.rs.next()) {
						u.stmt.executeUpdate("drop database user");
					}

					u.stmt.executeUpdate("create database user");
					u.stmt.executeUpdate("use user"); // 使company成为当前数据库
					u.stmt.executeUpdate(
							"create table user(id int(6) not null primary key,user char(10) not null,pass char(10) not null)");

					u.showmsg("创建数据库成功");
				} catch (SQLException e) {
					e.printStackTrace();
				}

				u.connclose();

			}
		});

		ServerSocket serversocket;
		try {
			serversocket = new ServerSocket(10001);
			while (true) {
				client = serversocket.accept();
				new Thread(new serverthread(client, userList)).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

上一篇:
java控制多个线程按照一定的顺序轮流执行
下一篇:
java简单连接数据库
标签:
网友评论
发布评论

访客的评论 2022/12/01 18:10

文中描述的是准确的吗,如何报名!

相关推荐
我也来发表评价关闭
我对该内容的评价:
0
评价500
验证码: 看不清 换一张
提交 (匿名发布,无须担心别人知道您的身份)