基于Java原生SercerSocket和I/O流进行登录注册接口实现,可部署服务端前端直接调用接口

基于Java原生SercerSocket和I/O流进行登录注册接口实现,可部署服务端前端直接调用接口

渡星河
2023-02-02 / 0 评论 / 6 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年02月02日,已超过595天没有更新,若内容或图片失效,请留言反馈。

SeversSockrt

基于Java原生SercerSocket和I/O流进行登录注册接口实现,可部署服务端前端直接调用接口

可以通过使用线程池和循环来对服务端进行简单优化

采用get方式进行访问

-------------------必看-------------------

必须修改RequestData中 //用户目录位置

    private final String userPath = "E:\\Users\\";
    请修改为你自己的,否则会报错,这里以Windows系统路径测试,其它系统请使用其它系统路径格式

用户保存位置方式

例子一个用户 账号为123456
那么在本地的文件保存为E:\Users\123456
密码保存为E:\Users\123456\password.txt
注册的时候会通过数据分析自动创建账户和密码文件夹和文件(采用IO流)

接口格式

## 登录接口
http://localhost/api/login?user=用户名&password=密码
## 注册接口
http://localhost/api/register?user=用户名&password=密码
可以添加其它数据,按照格式添加 &[数据名]=[数据] 例如 http://localhost/api/register?user=用户名&password=密码&name=张山

接口格式解析

http://localhost/api/login?user=用户名&password=密码
localhost 为服务器IP
api 文件夹
login 文件夹下的login类
问号后面为提交的数据

目录结构

建议

对前后端数据进行加密,例如aes加密。对数据作过期验证。

NbServer

package MuDaoServer;

import java.net.ServerSocket;
import java.net.Socket;

public class NbServer extends ServerMethod{
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(80);
        Socket socket = serverSocket.accept();
        //处理前端数据
        getClientData(socket);
        //反射获得需要输出的数据
        String val = reflex(RequestData.FullName);
        //输出数据
        ServerMethod.outBrowse(socket,val);
        socket.close();
    }
}

ServerMethod

package MuDaoServer;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.URL;
import java.util.Objects;
//导入api文件夹下面的所有类,用于获取路径
import MuDaoServer.Controller.Annotations;
import MuDaoServer.api.*;

public class ServerMethod extends RequestData{
    //获取用户客户端信息
    public static void getClientData(Socket socket) throws IOException {
        //获取客户端内容
        InputStream getBrowserData = socket.getInputStream();
        //将字节流转换为字符流
        InputStreamReader change = new InputStreamReader(getBrowserData);
        BufferedReader reader = new BufferedReader(change);
        String val;
        //获取第一行,用于解析用户使用了哪个文件,提交了哪些数据
        String line1 = reader.readLine();
        RequestData.firstLineData=line1;
        //将第一行以空格进行分割分别得到提交方法,提交路径数据,http协议版本  GET / HTTP/1.1,这里我们只需要路径
        RequestData.data = line1.split(" ")[1];
        //判断获取的路径是否包含/api/数据,不包含则返回错误json,目前只提供api文件夹下的文件
        if (RequestData.data.contains("/api/")){
            //将问号前面的数据放到RequestData中的path中
            RequestData.path=RequestData.data.split("\\?")[0];
            //判断请求的类是否存在 GET /api/login?user=202228902&password=QWERTY HTTP/1.1
            String className = RequestData.data.split("\\?")[0].split("/")[2];//获取类名
            String path = ServerMethod.class.getResource("./") +"api/"+className+".class";
            path = path.substring(6);
            path = path.replaceAll("/","\\\\\\\\");
            //判断文件是否存在
            if (fileExists(path)){
                //把全限定名放到数据中
                String[] split = ServerMethod.class.getResource("./").toString().split("/");
                String fullName = split[split.length - 1]+".api."+className;
                RequestData.FullName=fullName;
                System.out.println("全限定"+fullName);
            }else {
                val = "{\"code\":\"-1\",\"msg\":\"该接口不存在\"}";
                outBrowse(socket,val);
            }
        }else {
            val = "{\"code\":\"-1\",\"msg\":\"该接口不存在\"}";
            outBrowse(socket,val);
        }
    }
    //反射
    public static String reflex(String fullName) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> clazz = Class.forName(fullName);
        String invoke = "{\"code\":\"-1\",\"msg\":\"反射出错\"}";;
        //判断是否使用了注解
        if (clazz.isAnnotationPresent(Annotations.class)) {
            Annotations annotation = clazz.getAnnotation(Annotations.class);
            //获取注解的value
            String value = annotation.value();
            //判断注解中路径是否正确,
            if (value.equals(RequestData.path)) {
                //通过反射创建该servlet对象,然后调用该对象的service方法
                Object instance = clazz.getDeclaredConstructor().newInstance();
                Method method = clazz.getDeclaredMethod("service");
                //把类型强转为字符串
                invoke = (String) method.invoke(instance);
            }
        }
        return invoke;
    }
    //通用输出到网页
    public static void outBrowse(Socket socket,String value) throws IOException {
        String stringBuilder = "HTTP/1.1" + " " + 200 + " " +
                "ok" + "\n" +
                "Content-Type" + ":" + "text/html;charset=UTF-8" + "\n" +
                "\n" + value;
        OutputStream outputStream = socket.getOutputStream();
        PrintWriter output = new PrintWriter(outputStream);
        output.println(stringBuilder);
        output.flush();
        outputStream.close();
    }
    //判读文件或者文件夹是否存在
    public static boolean fileExists(String path) {
        File file = new File(path);
        return file.exists();
    }
    //创建一个文件
    public static boolean createFile(String path) throws IOException {
        File file = new File(path);
        return file.createNewFile();
    }
    //获取api文件夹下的类路径
    public static String classPath(String className) {

        URL url = login.class.getResource("./");
        return "";
    }
}

注解Annotations

package MuDaoServer.Controller;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Annotations {
    String value() default "";
}

RequestData 数据存放

package MuDaoServer;

import java.util.Map;

public class RequestData {
    //用户目录位置
    private final String userPath = "E:\\Users\\";

    public String getUserPath() {
        return userPath;
    }

    //存放类名
    private String clazz;
    //请求方法get/post
    private String method;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    //请求数据
    public static String data;
    //全限定名
    public static String FullName;
    //用户访问的接口路径
    public static String path;
    //存放第一行数据
    public static String firstLineData;

    public String getFirstLineData() {
        return firstLineData;
    }

    public void setFirstLineData(String firstLineData) {
        RequestData.firstLineData = firstLineData;
    }

    //存放其他头文件数据
    private Map<String, String> headers;

    public String getClazz() {
        return clazz;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }


    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    @Override
    public String toString() {
        return "RequestData{" +
                "clazz='" + clazz + '\'' +
                ", method='" + method + '\'' +
                ", path='" + path + '\'' +
                ", firstLineData='" + firstLineData + '\'' +
                ", headers=" + headers +
                '}';
    }
}

login 登录代码逻辑

package MuDaoServer.api;

import MuDaoServer.Controller.Annotations;
import MuDaoServer.RequestData;
import java.io.*;

@Annotations("/api/login")
public class login {
    public String service() throws IOException {
        String[] split = RequestData.data.split("&");
        String user = split[0].split("=")[1];
        String pass = split[1].split("=")[1];
        File file = new File("E:\\Users");
        String json = "";
        if (!file.exists()) {
            file.mkdirs();
            json="{\"code\":\"-1\",\"msg\":\"提交参数不完整\"}";
        }else {
            File file1 = new File("E:\\Users\\"+user);
            if (!file1.exists()) {
                json="{\"code\":\"-1\",\"msg\":\"用户不存在\"}";
            }else {
                BufferedReader bufferedReader = new BufferedReader(new FileReader("E:\\Users\\"+user+"\\password.txt"));
                if (pass.equals(bufferedReader.readLine())){
                    json="{\"code\":\"200\",\"msg\":\"登录成功\"}";
                }else {
                    json="{\"code\":\"-1\",\"msg\":\"密码错误\"}";
                }
            }
        }
        return json;
    }

}

register注册代码逻辑

package MuDaoServer.api;

import MuDaoServer.Controller.Annotations;
import MuDaoServer.RequestData;
import java.io.*;
import java.util.HashMap;

import static MuDaoServer.ServerMethod.fileExists;

@Annotations("/api/register")
public class register {
    public String service() throws IOException {
        String json = "";
        //获取data的数据
        String data = RequestData.data.split("\\?")[1];
        System.out.println("data:"+data);
        //对data数据进行分析
        HashMap<String, String> dataMap = new HashMap<>();//存放get请求的数据
        String[] split = data.split("&");
        for (String s : split){
            String[] split1 = s.split("=");
            dataMap.put(split1[0],split1[1]);
        }
        //判断必填数据是否存在
        if (dataMap.containsKey("user") && dataMap.containsKey("password")){
            //判断用户是否存在
            RequestData requestData = new RequestData();
            if (!fileExists(requestData.getUserPath()+dataMap.get("user"))){
                String path1 = requestData.getUserPath()+dataMap.get("user");
                File file = new File(path1);
                //创建用户文件夹
                boolean mkdirs = file.mkdirs();
                if (mkdirs){
                    //创建文件
                    FileOutputStream out = new FileOutputStream(path1 + "\\\\\\\\password.txt");
                    //写入文件
                    out.write(dataMap.get("password").getBytes());
                    out.close();
                    json = "{\"code\":\"200\",\"msg\":\"账号注册成功\"}";
                }
            }else {
                json = "{\"code\":\"-1\",\"msg\":\"该账号已存在\"}";
            }
        }else {
            json = "{\"code\":\"-1\",\"msg\":\"提交参数不完整\"}";
        }
        return json;
    }

}

获取用户列表

package MuDaoServer.api;

import MuDaoServer.Controller.Annotations;
import java.io.*;
import java.util.Arrays;

@Annotations("/api/listUser")
public class listUser {
    public String service() throws IOException {
        File file = new File("E:\\Users");
        File[] files = file.listFiles();
        String value =Arrays.toString(files);
        System.out.println(value);
        return value;
    }

}

有什么错误请评论交流

0

评论 (0)

取消