<b id="yt35u"></b>
  • <b id="yt35u"></b>

  • <tt id="yt35u"><form id="yt35u"></form></tt>
    <button id="yt35u"></button>

    <button id="yt35u"></button>

    <strike id="yt35u"><dfn id="yt35u"></dfn></strike>

    <i id="yt35u"></i>
    1. <tt id="yt35u"></tt>
      <b id="yt35u"><sub id="yt35u"><tr id="yt35u"></tr></sub></b>

      教育路上

      全國站>Java>網絡編程>java聊天室綜合案例
      學員需求

      java聊天室綜合案例

      摘要:java綜合案例,java 綜合 案例。以下是我們為大家整理的,相信大家閱讀完后肯定有了自己的選擇吧。

      2022-07-02 16:25網絡推薦

      發布時間:
      2022-07-02 16:25
      信息來源:
      網絡推薦
      瀏覽次數:
      1864
      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簡單連接數據庫
      標簽:
      網友評論
      發布評論

      訪客的評論 2024/07/10 12:45

      文中描述的是準確的嗎,如何報名!

      相關推薦
      我也來發表評價關閉
      我對該內容的評價:
      0
      評價500
      驗證碼: 看不清 換一張
      提交 (匿名發布,無須擔心別人知道您的身份)
      學校免費發布信息關閉
      我們審核后會盡快展示,如有圖片請發郵件到:edu63@foxmail.com

      姓      名:

      內      容:

      手機號碼:

      驗  證  碼:  換一張

      確認提交
      填寫需求信息關閉
      我們會根據您的需求匹配并審核留言

      姓      名:

      意向城市:

      留      言:

      手機號碼:

      驗  證  碼:  換一張

      確認提交
      完善補充本文信息關閉
      非常感謝您幫助完善補充本文信息


       換一張

      確認提交
      女班长给我看她的小内内

        <b id="yt35u"></b>
    1. <b id="yt35u"></b>

    2. <tt id="yt35u"><form id="yt35u"></form></tt>
      <button id="yt35u"></button>

      <button id="yt35u"></button>

      <strike id="yt35u"><dfn id="yt35u"></dfn></strike>

      <i id="yt35u"></i>
      1. <tt id="yt35u"></tt>
        <b id="yt35u"><sub id="yt35u"><tr id="yt35u"></tr></sub></b>