网络编程_TCP交流

LoginTwoWayClient

package TCP;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class LoginTwoWayClient {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        System.out.println("------client----------");
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        
        System.out.println("请输入用户名");
        String uname = console.readLine();
        System.out.println("请输入密码");
        String upwd = console.readLine();
        //建立连接  使用socket创建客户端 + 服务的地址和端口
        Socket client = new Socket("localhost",8888);
        //操作输入输出
        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
        dos.writeUTF("uname=" + uname + "&" + "upwd=" + upwd);
        dos.flush();
        DataInputStream dis = new DataInputStream(client.getInputStream());
        String result = dis.readUTF();
        System.out.println(result);
        dis.close();
        dos.close();
        client.close();
    }
}

 

LoginTwoWayServer

package TCP;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class LoginTwoWayServer {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        System.out.println("-------Server--------");
        ServerSocket sever = new ServerSocket(8888);
        //2.阻塞式等待连接accept
        Socket client = sever.accept();
        System.out.println("一个客户端建立了连接");
        //3.操作 输入输出流操作
        DataInputStream dis = new DataInputStream(client.getInputStream());
        String datas = dis.readUTF();
        String uname = "";
        String upwd = "";
        String[]dataArray = datas.split("&");
        for(String s:dataArray) {
            String[]userinfo = s.split("=");
            if(userinfo[0].equals("uname")) {
                System.out.println("你的用户名为"+userinfo[1]);
                uname = userinfo[1];
            }
            else if(userinfo[0].equals("upwd")){
                System.out.println("你的用户名为"+userinfo[1]);
                upwd = userinfo[1];
            }
        }
        //输出
        DataOutputStream dos = new DataOutputStream(client.getOutputStream());    
        if(uname.equals("wcy") && upwd.equals("wcy")) {
            dos.writeUTF("登入成功,欢迎回来");
            
        }else {
            dos.writeUTF("登入失败,账号密码不匹配");
        }
        dos.flush();
        dos.close();
        dis.close();
        client.close();
    }
}

 

posted @ 2020-12-27 15:28  冰糖葫芦很乖  阅读(76)  评论(0编辑  收藏  举报