TCP客户端和服务器通信以及访问数据库

Client

package com.qf.lianxi;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        //建立服务器的连接
        try(Socket socket = new Socket(InetAddress.getByName("10.36.140.99"),7777);) {
            //将账号密码写入网络
            OutputStream outputStream = socket.getOutputStream();
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入账号:");
            String username = sc.next();
            System.out.println("请输入密码:");
            String password = sc.next();

            outputStream.write(("signal:login,username:"+username+",password:"+password).getBytes("utf-8"));
            outputStream.flush();
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[100];
            int num = inputStream.read(bytes);
            String data = new String(bytes,0,num);
            System.out.println(data);

            //重置密码
            if (data!=null && data.length()!=0){
                System.out.println("跳转到主界面,欢迎:"+data);

                Socket socket1 = new Socket(InetAddress.getByName("10.36.140.99"),7777);

                //将数据二次写入服务器
                OutputStream outputStream1 = socket1.getOutputStream();
                System.out.println("请输入新密码:");
                String newPWD = sc.next();
                outputStream1.write(("signal:reset,username:"+username+",password:"+newPWD).getBytes("utf-8"));
                outputStream1.flush();
                InputStream inputStream1 = socket1.getInputStream();
                byte[] bytes1 = new byte[100];
                int num1 = inputStream1.read(bytes1);
                String data1 = new String(bytes1,0,num1);
                System.out.println(data1);
            }else {
                System.out.println("登录失败,请重新登录!");
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Server

package com.qf.lianxi;

import com.qf.util.DBUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Server {
    public static void main(String[] args) {
        //实例化一个ServerSocket
        try(ServerSocket serverSocket = new ServerSocket(7777)) {
            while (true){
                //2.监听,接受客户端的信息
                System.out.println("服务器正常启动,等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("客户端连接成功");
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[100];
                int num = inputStream.read(bytes);
                String data = new String(bytes,0,num);
                System.out.println("用户的信息:"+data);

                //访问数据库
                //进行简单的处理,将数据从字符串里面取出来
                int index = data.indexOf(",");
                String signalStr = data.substring(0,index);
                //判断是登录还是重置密码
                String[] strings = signalStr.split(":");
                String signal = "";
                if ("signal".equals(strings[0])){
                    signal = strings[1];
                }else {
                    System.out.println("无法完成功能!");
                }

                //验证完成开始完成功能
                String temp = "";
                String dataStr = data.substring(index + 1, data.length());
                User user = new User(dataStr);
                if ("login".matches(signal)) {
                    User tempUser = fingUser(user);

                    if (tempUser != null) {
                        temp = tempUser.getUsernmae();
                    } else {
                        temp = "";
                    }
                }else if ("reset".equals(signal)){
                    int value = reSetPwd(user);
                    System.out.println("value = " + value);
                    if (value == 0){
                        temp = "重置失败";
                    }else {
                        temp = "重置成功!";
                    }
                }
                //将值返回客户端,告知客户端
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write("重置成功".getBytes("utf-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //重置密码
    public static int reSetPwd(User user){
        Connection connection = null;
        PreparedStatement statement = null;
        User user1 = null;
        int num = 0;
        try {
//            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //获取连接
            connection = DBUtils.getConnection();
            String sql = "update user set password=? where username=?";//?占位符
            statement = connection.prepareStatement(sql);
            statement.setString(2,user.getUsernmae());
            statement.setString(1,user.getPassword());
            num = statement.executeUpdate();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(connection,statement,null);
        }
        return num;
    }

    //登录
    public static User fingUser(User user){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        User user1 = null;
        try {
//            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //获取连接
            connection = DBUtils.getConnection();
            String sql = "select * from user where username=? and password=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,user.getUsernmae());
            statement.setString(2,user.getPassword());
            rs = statement.executeQuery();
            if (rs.next()){
                user1 = new User(rs.getString("username"),rs.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
          DBUtils.closeAll(connection,statement,rs);
        }
        return user1;
    }
}

实体类User

package com.qf.lianxi;

public class User {
    private String usernmae;
    private String password;

    public User() {
    }

    public User(String line){
        String[] strings = line.split(",");
        for (String string : strings) {
            String[] pair = string.split(":");
            String key = pair[0];
            String value = pair[1];
            if ("username".matches(key)){
                this.usernmae = value;
            }else if ("password".equals(key)){
                this.password = value;
            }
        }
    }

    public User(String usernmae, String password) {
        this.usernmae = usernmae;
        this.password = password;
    }

    public String getUsernmae() {
        return usernmae;
    }

    public void setUsernmae(String usernmae) {
        this.usernmae = usernmae;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "usernmae='" + usernmae + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

工具类DBUtils

package com.qf.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DBUtils {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    static {
        try{
            Properties properties = new Properties();
            properties.load(new FileReader("D:\\IDEA文档\\dashuju\\Day8.16\\src\\com\\qf\\util\\DBConfig.properties"));
            driver = properties.getProperty("mydriver");
            url = properties.getProperty("myurl");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }



    public static void closeAll(Connection connection, Statement statement, ResultSet rs){
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值