TCP基本步骤

作者: kanaSki | 来源:发表于2019-07-04 21:21 被阅读0次

    分析:
    1.TCP协议基于请求-响应模式
    2.在网络通讯中,第一次主动发起通讯的程序被称作客户端程序
    3.第一次通讯中等待连接的程序被称作服务器端程序
    4.利用IO流实现数据的传输

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class LoginServer {
        public static void main(String[] args) throws IOException {
            ServerSocket server = new ServerSocket(8888);
            Socket accept = server.accept();
            String uname = "";
            String upwd = "";
            DataInputStream dis = new DataInputStream(accept.getInputStream());
            String s = dis.readUTF();
            String[] dataArray = s.split("&");
            for (String data : dataArray) {
                String[] userInfo = data.split("=");
                if (userInfo[0].equals("uname")) {
                    uname = userInfo[1];
                }
                if (userInfo[0].equals("upwd")) {
                    upwd = userInfo[1];
                }
            }
            DataOutputStream dos = new DataOutputStream(accept.getOutputStream());
            if (uname.equals("katsuna") && upwd.equals("kotonoha")) {
                dos.writeUTF("成功");
            } else {
                dos.writeUTF("失败");
            }
            dos.flush();
            dos.close();
            dis.close();
            accept.close();
            server.close();
        }
    }
    
    
    import java.io.*;
    import java.net.Socket;
    
    /**
     * 模拟登陆
     */
    public class LoginClient {
        public static void main(String[] args) throws IOException {
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("请输入用户名");
            String uname = console.readLine();
            System.out.println("请输入密码");
            String upwd = console.readLine();
            Socket client = new Socket("127.0.0.1", 8888);
            DataOutputStream dos = new DataOutputStream(client.getOutputStream());
            dos.writeUTF("uanme=" + uname + "&upwd=" + upwd);
            dos.flush();
            DataInputStream dis = new DataInputStream(client.getInputStream());
            String s = dis.readUTF();
            System.out.println(s);
            dis.close();
            dos.close();
            client.close();
        }
    }
    
    

    相关文章

      网友评论

        本文标题:TCP基本步骤

        本文链接:https://www.haomeiwen.com/subject/jrghhctx.html