Java CS聊天 聊天记录实时上传数据库与txt文本

2020-12-27 00:00:00 文本 实时 聊天记录

Java中CS聊天室是一个非常经典的项目,有很多实现方式,这在网络上能找到很多。但是一般都是实现了正常的聊天功能,聊天记录不能留存下来。

Java Eclipse如何与Oracle连接可以查看上一篇博客,有详细代码和操作,如果会将txt文本文档中的内容同步到数据库中,将聊天记录同步到数据库并且写入txt文本文档也就很简单了。

首先是DBUtil类,和上一篇没有区别

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DButil {
	
	public final static String URL = "jdbc:oracle:thin:@localhost:1521:xe";
	public final static String USERNAME ="xxx";
	public final static String PWD = "xxx";
	public final static String DRIVER = "oracle.jdbc.driver.OracleDriver";
	
	static{
		try{
			Class.forName(DRIVER);
			System.out.println("成功");
		}catch (ClassNotFoundException e){
			System.out.println("失败");
			e.printStackTrace();
		}
	}
	
	public Connection getConnection() throws SQLException{
		Connection conn = null;
		conn = DriverManager.getConnection(URL,USERNAME,PWD);
		return conn;
	}
	
	public void closaAll(ResultSet rst,Statement stmt,Connection conn){
		if(rst!= null){
			try{
				rst.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		
		if(stmt!= null){
			try{
				stmt.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		
		if(conn!= null){
			try{
				conn.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
	}
	
	
}

然后是一个同步到数据库的工具类Oracle类

package chat;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import util.DButil;

public class Oracle {
	public void tongbu(String send,String receive,String con,String date){
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		DButil db = new DButil();
		try{
			conn = db.getConnection();
			String sql1 = "select seq_rec.nextval as id from dual";
			PreparedStatement st1=conn.prepareStatement(sql1);
			String sql2="insert into chatrec(sender,receiver,con,pid,time) values(?,?,?,?,to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'))";
			rst = st1.executeQuery();
			rst.next();
			int id = rst.getInt(1);
			rst.close();
			PreparedStatement st2=conn.prepareStatement(sql2);
			st2.setString(1, send);
			st2.setString(2,receive);
			st2.setString(3,con);
			st2.setInt(4,id);
			st2.setString(5, date);
			st2.executeUpdate();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			
			db.closaAll(rst, stmt, conn);
		}
	}
}

这个类的几个参数可以将发送者接收者,聊天内容和发送时间记录下来,当然pid这个列和上一篇的作用一样,是一个sequence用来排序。当然不推荐大家使用我这篇的风格,最好将pid放在第一栏中,这样别人查看数据库的时候就可以直接跳过第一栏查看后面的数据,增加了数据库的可读性,我这里就懒得改了。

然后是非常经典的服务器和客户端代码,聊天记录同步到txt文本直接写在服务器和客户端代码内部了,当然其实更推荐的是和数据库的处理方法一样,将这个功能单独拿出来写成一个工具类,以后还要再别的类中就可以直接调用了。

服务器代码如下

package chat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import util.DButil;

public class Server {
    static ServerSocket serverSocket = null;
    public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		DButil db = new DButil();
		BufferedWriter write =null;
        Oracle oracle = new Oracle();
        try {
            //1创建服务端对象。
            serverSocket = new ServerSocket(8868);
            //2,获取连接过来的客户端对象。
            Socket socket = serverSocket.accept();
            System.out.println("来自客户端【" + socket.getInetAddress().getHostAddress() + "】的连接");
            BufferedReader bufferedReader = null;
            BufferedReader bufferedReader_SystemIN = null;
            BufferedWriter bufferedWriter = null;
            //3,通过socket对象获取输入流,要读取客户端发来的数据
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //4,通过字符输入流获取键盘输入,要读取控制台写给客户端的数据
            bufferedReader_SystemIN = new BufferedReader(new InputStreamReader(System.in));
            //5.使用客户端socket对象的输出流给客户端返回数据
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String message = "";
            write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\luyh\\Desktop\\record.txt",true)));             
            while ((message = bufferedReader.readLine()) != null) {
            	Date date = new Date();
            	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	String time = df.format(date);
            	System.out.print(time);
                System.out.println("来自客户端【" + socket.getInetAddress().getHostAddress() + "】说:" + message);
                System.out.print("请输入:");
                String s = bufferedReader_SystemIN.readLine();
                bufferedWriter.write(s);
                bufferedWriter.newLine();
                bufferedWriter.flush();
                write.write("客户端对服务器说");
                write.write(s);
                write.newLine();
                write.flush();
                oracle.tongbu("客户端", "服务器", s,time);
           }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(null != write){
            	try {
					write.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
            db.closaAll(rst, stmt, conn);
        }
    }
}

客户端代码如下

package chat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import util.DButil;

public class Client {

    public static void main(String[] args) {
	Connection conn = null;
	Statement stmt = null;
	ResultSet rst = null;
	DButil db = new DButil();
	BufferedWriter write =null;
        Socket socket = null;
        BufferedReader bufferedReader = null;
        BufferedReader bufferedReader_Server = null;
        BufferedWriter bufferedWriter = null;
        Oracle oracle = new Oracle();
        
        try {
            //1,创建socket客户端对象。
            socket = new Socket("127.0.0.1", 8868);
            //2,获取键盘录入。获取控制台用户输入的信息
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            //3,socket输入流。读取服务端返回的数据
            bufferedReader_Server = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //4,socket输出流。将控制台信息数据输出给服务端
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            System.out.print("请输入:");
            String message = "";
            write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\luyh\\Desktop\\record.txt",true)));             

            while ((message = bufferedReader.readLine()) != null) {
            	Date date = new Date();
            	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	String s = df.format(date);
            	bufferedWriter.write(message);
                bufferedWriter.newLine();
                bufferedWriter.flush();
                String getMessage = bufferedReader_Server.readLine();
                System.out.print(s);
                System.out.println("来自服务器说:" + getMessage);
                System.out.print("请输入:");
                write.write("服务器对客户端说");
                write.write(message);
                write.newLine();
                write.flush();
                oracle.tongbu("服务器", "客户端", message,s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(null != write){
            	try {
			write.close();
		} catch (IOException e) {
		// TODO Auto-generated catch block
			e.printStackTrace();
		}
            }
            db.closaAll(rst, stmt, conn);
        }

    }
}

代码运行效果如下

《Java CS聊天 聊天记录实时上传数据库与txt文本》

同步到数据库中的效果如下

 《Java CS聊天 聊天记录实时上传数据库与txt文本》

PID那一栏是以前测试过,已经到了51,如果向从头来,按照Oracle中的操作,需要将sequence删除掉重写创建。具体操作可以参考我以前的博客

写入txt效果如下

 《Java CS聊天 聊天记录实时上传数据库与txt文本》

 

    原文作者:TogashiRikka
    原文地址: https://blog.csdn.net/l13913849831/article/details/107814849
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章