标签:
//QQ聊天程序的建立网络流类
import java.net.*;
import java.io.*;
public class Neter {
private BufferedReader br;
private PrintWriter pw;
public Neter(Socket socket){
try{
InputStream is=socket.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
br=new BufferedReader(isr);
OutputStream os=socket.getOutputStream();
OutputStreamWriter osw=new OutputStreamWriter(os);
pw=new PrintWriter(osw,true);
}catch(Exception e){
e.printStackTrace();
}
}
public void send(String message){
try{
pw.println(message);
}catch(Exception e){
e.printStackTrace();
}
}
public String recieve(){
String message="";
try{
message=br.readLine();
}catch(Exception e){
e.printStackTrace();
}
return message;
}
}
//QQ聊天程序的数据库验证类
import java.sql.*;
import java.io.*;
public class SQLer {
public boolean select(String u,String p){
boolean b=false;
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
File f=new File("F:/java/SQL.ini");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String driver=br.readLine();
String url=br.readLine();
String user=br.readLine();
String pass=br.readLine();
Class.forName(driver);
con=DriverManager.getConnection(url,user,pass);
ps=con.prepareStatement("select username,password from user where username=? and password=?");
ps.setString(1, u);
ps.setString(2, p);
rs=ps.executeQuery();
b=rs.next();
br.close();
rs.close();
ps.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
rs.close();
ps.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
return b;
}
}
//QQ聊天程序的文件读写类
import java.io.*;
public class Recorder {
private File f;
public Recorder(String url){
try{
f=new File(url);
if(!f.exists()){
f.createNewFile();
}
}catch(Exception e){
e.printStackTrace();
}
}
public void write(String message){
try{
FileWriter fw=new FileWriter(f,true);
PrintWriter pw=new PrintWriter(fw);
pw.println(message);
pw.close();
}catch(Exception e){
e.printStackTrace();
}
}
public String read(){
String message="";
try{
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
message+=br.readLine()+"\n";
}catch(Exception e){
e.printStackTrace();
}
return message;
}
}
服务器
//QQ聊天程序服务器代码
import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
public class QQServer {
private ServerSocket server;
private Socket socket;
private Neter net;
private HashMap<String,Neter> hm;
public QQServer(){
createSocket();
}
public void createSocket(){
try{
server=new ServerSocket(8000);
hm=new HashMap<String,Neter>();
System.out.println("服务器已启动!");
while(true){
socket=server.accept();
net=new Neter(socket);
// MyService ms=new MyService(socket);
MyService ms=new MyService(net,hm);
Thread t=new Thread(ms);
t.start();
System.out.println("客户端已连上!");
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
new QQServer();
}
}
class MyService implements Runnable{
// private Socket socket;
private HashMap<String,Neter> hm;
private Neter net;
// public MyService(Socket socket){
// this.socket=socket;
// }
public MyService(Neter net,HashMap<String,Neter> hm){
this.net=net;
this.hm=hm;
}
@Override
public void run(){
createStream();
}
public void createStream(){
try{
//输入流
// InputStream is=socket.getInputStream();
// InputStreamReader isr=new InputStreamReader(is);
// BufferedReader br=new BufferedReader(isr);
// //输出流
// OutputStream os=socket.getOutputStream();
// OutputStreamWriter osw=new OutputStreamWriter(os);
// PrintWriter pw=new PrintWriter(osw,true);
while(true){
// str=br.readLine();
String str=net.recieve();
String type=str.split("%")[0];
String mess=str.split("%")[1];
if(type.equals("[login]")){
String user=mess.split(":")[0];
String pass=mess.split(":")[1];
SQLer sql=new SQLer();
if(sql.select(user,pass)){
net.send("[login]%OK");
for(Neter n:hm.values()){
n.send("[add]%"+user);
}
for(String s:hm.keySet()){
net.send("[add]%"+s);
}
hm.put(user, net);
}else{
net.send("[login]%ERR");
}
// Connection con=null;
// PreparedStatement ps=null;
// ResultSet rs=null;
// try{
// Class.forName("org.gjt.mm.mysql.Driver");
// con=DriverManager.getConnection("jdbc:mysql://localhost:3306/qq","root","root");
// ps=con.prepareStatement("select username,password from user where username=? and password=?");
// ps.setString(1, user);
// ps.setString(2, pass);
// rs=ps.executeQuery();
//
// if(rs.next()){
// pw.println("[LOGIN]:OK");
// }else{
// pw.println("[LOGIN]:NO");
// }
// rs.close();
// ps.close();
// con.close();
// }catch(Exception e1){
// e1.printStackTrace();
// }
// finally{
// try{
// rs.close();
// ps.close();
// con.close();
// }catch(Exception e1){
// e1.printStackTrace();
// }
// }
}else if(type.equals("[chat]")){
String from=mess.split(":")[0];
String to=mess.split(":")[1];
String message=mess.split(":")[2];
Neter ts=hm.get(to);
ts.send("[chat]%"+from+":"+message);
}else if(type.equals("[exit]")){
for(Neter n:hm.values()){
n.send("[exit]%"+mess);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
界面:
//QQ聊天程序的登录界面及相关事件
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.net.Socket;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class QQLogin extends JFrame implements ActionListener,WindowListener{
private JLabel labUser; //用户标签
private JLabel labPass; //密码标签
private JTextField txtUser; //用户信息输入框
private JPasswordField txtPass; //用户密码输入框
private JButton btnReg; //注册按钮
private JButton btnLogin; //登录按钮
private JButton btnCancel; //取消按钮
private JPanel jpCenter; //中部布局
private JPanel jpSouth; //南部布局
private Socket socket;
private Neter net;
public QQLogin(){
try{
socket=new Socket("localhost",8000);
net=new Neter(socket);
}catch(Exception e){
e.printStackTrace();
}
init();
this.setSize(300,150);
this.setResizable(false);
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(500,200);
}
//界面布局
public void init(){
//用户标签和密码标签
labUser=new JLabel("用户");
labPass=new JLabel("密码");
//用户和密码输入框
txtUser=new JTextField();
txtPass=new JPasswordField();
//按钮
btnReg=new JButton("注册");
btnReg.addActionListener(this);
btnLogin=new JButton("登录");
btnLogin.addActionListener(this);
btnCancel=new JButton("取消");
btnCancel.addActionListener(this);
//中部布局
jpCenter=new JPanel();
jpCenter.setLayout(new GridLayout(2,2));
jpCenter.add(labUser);
jpCenter.add(txtUser);
jpCenter.add(labPass);
jpCenter.add(txtPass);
this.add(jpCenter,BorderLayout.CENTER);
//南部布局
jpSouth=new JPanel();
jpSouth.setLayout(new FlowLayout());
jpSouth.add(btnReg);
jpSouth.add(btnLogin);
jpSouth.add(btnCancel);
this.add(jpSouth,BorderLayout.SOUTH);
this.addWindowListener(this);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("登录")){
try{
// OutputStream os=socket.getOutputStream();
// OutputStreamWriter osw=new OutputStreamWriter(os);
// PrintWriter pw=new PrintWriter(osw,true);
//
// InputStream is=socket.getInputStream();
// InputStreamReader isr=new InputStreamReader(is);
// BufferedReader br=new BufferedReader(isr);
String user=txtUser.getText();
String pass=new String(txtPass.getPassword());
if(!user.equals("")&&!pass.equals("")){
// pw.println("[LOGIN]:"+user+"%"+pass);
//
// String login=br.readLine();
net.send("[login]%"+user+":"+pass);
String login=net.recieve();
// System.out.println(login.split(":")[0]);
if(login.split("%")[0].equals("[login]")){
String str=login.split("%")[1];
if(str.equals("OK")){
QQMain main=new QQMain();
// main.setSocket(socket);
main.setNeter(net, user);
main.setVisible(true);
this.setVisible(false);
}else{
JOptionPane.showMessageDialog(this, "用户名或密码错误!");
}
}
}else{
JOptionPane.showMessageDialog(this,"密码或用户名为空!");
}
}catch(Exception e1){
}
}
if(e.getActionCommand().equals("注册")){
QQReg r=new QQReg();
r.setVisible(true);
}
if(e.getActionCommand().equals("取消")){
txtUser.setText("");
txtPass.setText("");
}
}
public String getUser(){
return txtUser.getText();
}
public String getPass(){
return new String(txtPass.getPassword());
}
public static void main(String[] args){
QQLogin login=new QQLogin();
login.setVisible(true);
}
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
int i=JOptionPane.showConfirmDialog(this, "是否关闭?","QQlogin",JOptionPane.OK_CANCEL_OPTION);
if(i==JOptionPane.OK_OPTION){
System.exit(1);
}
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
}
//QQ聊天程序注册界面
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class QQReg extends JFrame implements ActionListener{
JLabel labMess; //显示注册标签
JLabel labUser; //用户标签
JLabel labPass; //密码标签
JTextField txtUser; //用户输入框
JPasswordField txtPass; //密码输入框
JButton btnOK; //确认按钮
JButton btnCancel; //取消按钮
JPanel jpSouth;
JPanel jpCenter;
public QQReg(){
init();
this.setBounds(500,200,300,150);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void init(){
//实例化所有选项
labMess=new JLabel("注册信息");
labUser=new JLabel("用户");
labPass=new JLabel("密码");
txtUser=new JTextField();
txtPass=new JPasswordField();
btnOK=new JButton("确认");
btnOK.addActionListener(this);
btnCancel=new JButton("取消");
btnCancel.addActionListener(this);
jpSouth=new JPanel();
jpSouth.add(btnOK);
jpSouth.add(btnCancel);
jpCenter=new JPanel();
jpCenter.setLayout(new GridLayout(2,2));
jpCenter.add(labUser);
jpCenter.add(txtUser);
jpCenter.add(labPass);
jpCenter.add(txtPass);
this.add(labMess,BorderLayout.NORTH);
this.add(jpCenter,BorderLayout.CENTER);
this.add(jpSouth,BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand()=="确认"){
Connection con=null;
PreparedStatement ps=null;
String user=txtUser.getText();
String pass=new String(txtPass.getPassword());
try{
Class.forName("org.gjt.mm.mysql.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/qq","root","root");
ps=con.prepareStatement("insert into user(username,password) values(?,?)");
ps.setString(1,user);
ps.setString(2, pass);
ps.executeUpdate();
}catch(Exception e1){
e1.printStackTrace();
}
}
if(e.getActionCommand()=="取消"){
txtUser.setText("");
txtPass.setText("");
}
}
// public static void main(String[] args){
// QQReg r=new QQReg();
// r.setVisible(true);
// }
}
//QQ聊天程序主界面类
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.swing.JScrollPane;
public class QQMain extends JFrame implements ActionListener,Runnable,WindowListener{
private JTextArea txtSend; //发送信息的窗口
private JScrollPane scrollSend;
private JTextArea txtMess; //显示信息的窗口
private JScrollPane scrollMess;
private JButton btnSend; //发送按钮去
private JButton btnCancel; //取消按钮
private JButton btnMess; //显示消息按钮
private JComboBox jbList; //显示聊天对象的下拉列表
private JPanel jpSmall;
private JPanel jpBig;
private int score=0;
private QQChat chat;
// private Socket socket;
private Neter net;
private String user;
private Recorder record;
public QQMain(){
init();
chat=new QQChat();
this.setBounds(300,100,300,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
}
//界面布局按钮
public void init(){
txtSend=new JTextArea();
scrollSend=new JScrollPane(txtSend);
txtMess=new JTextArea();
scrollMess=new JScrollPane(txtMess);
txtMess.setEditable(false);
btnSend=new JButton("发送");
btnSend.addActionListener(this);
btnCancel=new JButton("取消");
btnMess=new JButton("聊天记录");
btnMess.addActionListener(this);
jbList=new JComboBox();
jpSmall=new JPanel();
jpSmall.add(jbList);
jpSmall.add(btnSend);
jpSmall.add(btnCancel);
jpSmall.add(btnMess);
jpBig=new JPanel();
jpBig.setLayout(new BorderLayout());
jpBig.add(jpSmall,BorderLayout.NORTH);
jpBig.add(scrollSend,BorderLayout.CENTER);
this.setLayout(new GridLayout(2,1));
this.add(scrollMess);
this.add(jpBig);
this.addWindowListener(this);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("发送")){
try{
// OutputStream os=socket.getOutputStream();
// OutputStreamWriter osw=new OutputStreamWriter(os);
// PrintWriter pw=new PrintWriter(osw,true);
String mess=txtSend.getText();
String to=jbList.getSelectedItem().toString();
if(!mess.equals("")){
// pw.println("[CHAT]:"+mess);
net.send("[chat]%"+user+":"+to+":"+mess);
txtSend.setText("");
}
// txtMess.append(mess+"\n");
// chat.getArea().append(mess+"\n");
}catch(Exception e1){
e1.printStackTrace();
}
}
if(e.getActionCommand().equals("聊天记录")){
score++;
if(score%2==1){
chat.setVisible(true);
}else{
chat.setVisible(false);
}
}
}
// public void writeChat(){
// try{
// File chat=new File("F:/java/chat.txt");
//
// FileWriter fw=new FileWriter(chat,true);
// PrintWriter pw=new PrintWriter(fw);
//
// String s=txtSend.getText();
// pw.println(s);
// pw.flush();
//
// }catch(Exception e){
// e.printStackTrace();
// }
// }
//
public void setNeter(Neter net,String user){
this.net=net;
this.user=user;
jbList.addItem(user);
this.setTitle(user);
record=new Recorder("F:/java/"+user+".txt");
chat.getArea().append(record.read());
Thread t=new Thread(this);
t.start();
}
@Override
public void run(){
while(true){
String str=net.recieve();
String type=str.split("%")[0];
String mess=str.split("%")[1];
if(type.equals("[chat]")){
String from=mess.split(":")[0];
String message=mess.split(":")[1];
txtMess.append(from+"说:"+message+"\n");
record.write(from+"说:"+message+"\n");
chat.getArea().append(from+"说:"+message+"\n");
}else if(type.equals("[add]")){
jbList.addItem(mess);
}else if(type.equals("[exit]")){
txtMess.append(mess+"已退出\n");
}
}
}
public static void main(String[] args){
QQMain main=new QQMain();
main.setVisible(true);
}
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
int i=JOptionPane.showConfirmDialog(this, "是否关闭?","QQchat",JOptionPane.OK_CANCEL_OPTION);
if(i==JOptionPane.OK_OPTION){
net.send("[exit]%"+user);
System.exit(1);
}else{
this.setVisible(true);
}
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
}
//QQ聊天程序聊天记录界面
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class QQChat extends JFrame{
private JTextArea areaMess;
private JScrollPane scrollMess;
public QQChat(){
areaMess=new JTextArea();
scrollMess=new JScrollPane(areaMess);
areaMess.setEditable(false);
// chatFile();
this.add(scrollMess);
this.setResizable(false);
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(620,100,300,400);;
}
public JTextArea getArea(){
return areaMess;
}
// public void chatFile(){
// try{
// File chat=new File("F:/java/chat.txt");
// FileReader fr=new FileReader(chat);
//
// BufferedReader br=new BufferedReader(fr);
//
// StringBuffer s=new StringBuffer();
// while(br.ready()){
// s.append(br.readLine()+"\n");
// }
// areaMess.setText(s.toString());
// }catch(Exception e){
// e.printStackTrace();
// }
// }
// public static void main(String[] args){
// QQChat chat=new QQChat();
// chat.setVisible(true);
// }
}
标签:
原文地址:http://www.cnblogs.com/YP-W-Ricardo/p/4316546.html