Socket TCP protocol-based multi-user network programming simulation landing

First, demand :

  • Complete multi-user network sign-on function

  • User name password, server login prompt success or failure

Second, the analysis:

  • Implementation uses Socket network programming based on TCP protocol
  • TCP protocol based on the request - response pattern
  • In network communication, first initiates communication program is called the client (Client) Program
  • The first notification procedure is referred to wait for a connection server (Server) Program
  • Use for data transmission stream IO
    Here Insert Picture Description

Third, the server

Thinking
1, designated port, used to create ServerSocket server;
2, blocking waits for a connection (Accept () method);
3, obtaining stream data I / O and analyzed;
4, release of resources;

Code:

  The specific operation encapsulated inside a class, when there is a client connected to the server you can create a child thread to achieve its function;

public class TCPServer {

	public static void main(String[] args) throws IOException {
        // 1、指定端口,使用ServerSocket创建服务器
        ServerSocket serverSocket = new ServerSocket(8888);
        // 2、阻塞式等待连接 accept
        boolean flag = true;
        while (flag) {
            Socket socket = serverSocket.accept();
            System.out.println("有一个客户端连接了服务器");
            new Thread(new Channel(socket)).start();

        }
        serverSocket.close();
    }

    static class Channel implements Runnable{
        private Socket socket;
        DataInputStream dis;  //输入流
        DataOutputStream dos; //输出流
        public Channel(Socket socket) {
            this.socket = socket;
            try {
                dis = new DataInputStream(this.socket.getInputStream());
                dos = new DataOutputStream(this.socket.getOutputStream()); 
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }

        }
        @Override
        public void run() {

            System.out.println("客户端连接成功");
            // 3、操作:输入输出流
            String uName = "";
            String uPwd = "";
            //分析数据
            String[] dataArray = receive().split("&");
            for (String info : dataArray) {
                String[] userInfo = info.split("=");

                if (userInfo[0].equals("userName")) {
                    System.out.println("你的用户名为:" + userInfo[1]);
                    uName = userInfo[1];
                } else {
                    System.out.println("你的密码为:" + userInfo[1]);
                    uPwd = userInfo[1];
                }
            }
            //输出
            if (uName.equals("daria") && uPwd.equals("123")) {
                send("登录成功");
            } else {
                send("用户名或密码错误,请重新输入");
            }
            release();


        }
        //接收数据
        private String receive() {
            String datas = "";
            try {
                datas = dis.readUTF();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return datas;
        }
        private void send(String msg) {
            try {
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        //释放资源
        private void release() {
            try {
                if (null != dos) {
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != dis) {
                    dis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != socket) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Fourth, the client

Ideas:

1. Create the Socket connection is established the client and server address + port;
2, data transmission or a data reception response through the I / O server flow;
3, end request, release of resources;

Code:

The transmitting and receiving data encapsulated into a respective internal class, easy maintenance;

public class TCPClient {
    static class Send { //发送消息
        private DataOutputStream dos;
        private Socket socket;
        private Scanner scanner;
        private String msg;
        public Send(Socket socket) {
            this.scanner = new Scanner(System.in);
            this.msg = this.init();
            this.socket = socket;
            try {
                dos = new DataOutputStream(this.socket.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        private void send() {

            try {
                dos.writeUTF(this.msg);
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        private String  init() {
            System.out.println("请输入用户名");
            String userName = this.scanner.nextLine();
            System.out.println("请输入密码");
            String userPwd = this.scanner.nextLine();
            return "userName=" + userName + "&" + "userPwd=" + userPwd;
        }

    }

    static class Receive { //接收消息
        private DataInputStream dis;
        Socket socket;
        public Receive(Socket socket) {
            this.socket = socket;
            try {
                dis = new DataInputStream(this.socket.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void receive() {
            String result = null;
            try {
                result = dis.readUTF();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(result);
        }
    }
    public static void main(String[] args) throws IOException {
        
        // 1、建立连接 使用Socket创建客户端+服务器地址和端口
        Socket socket = new Socket("127.0.0.1",8888);
        // 2、操作:输入输出流
        new Send(socket).send();
        new Receive(socket).receive();
        // 3、释放资源
        socket.close();
    }
}

Five test

  Because there is no connection to the database is unable to determine the user name with the correct password, so here we specified a user name and password daria 123 to verify the information input;
Open Server-side
Here Insert Picture Description
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/Daria_/article/details/90703537