package com.sundear.demo.tcp;
import java.io.*;
import java.net.Socket;
/**
* 模拟登录:双向
* 创建客户端
* 1。建立连接 使用Socket创建客户端+服务的地址和端口
* 2. 操作 输入输出流操作
* 3。 释放资源
*/
public class LoginTwoClient {
public static void main(String[] args) throws IOException {
System.out.println("---client---");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入用户名");
String username =br.readLine();
System.out.println("请输入密码");
String password =br.readLine();
Socket client =new Socket("localhost",8888);
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
dos.writeUTF("username="+username+"&"+"password="+password);
dos.flush();
DataInputStream dis = new DataInputStream(client.getInputStream());
String datas = dis.readUTF();
System.out.println(datas);
dos.close();
client.close();
}
}
package com.sundear.demo.tcp;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 模拟登录:双向
* 创建服务器
* 1。指定端口 使用ServerSocket创建服务器
* 2,阻塞式等待连接 accept
* 3. 操作 输入输出流操作
* 4。 释放资源
*/
public class LoginTwoServer {
public static void main(String[] args) throws IOException {
System.out.println("---server---");
//指定端口 使用ServerSocket创建服务器
ServerSocket server = new ServerSocket(8888);
//阻塞式等待连接 accept
Socket client = server.accept();
System.out.println("一个客户端建立了连接");
//操作 输入输出流操作
DataInputStream dis = new DataInputStream(client.getInputStream());
String data = dis.readUTF();
String username="";
String password="";
String[] datas=data.split("&");
for(String info:datas){
String[] user = info.split("=");
if(user[0].equals("username")){
System.out.println("你的用户名为"+user[1]);
username=user[1];
}else if(user[0].equals("password")){
System.out.println("你的密码为"+user[1]);
password=user[1];
}
}
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
if(username.equals("root")&&password.equals("sundear123")){
dos.writeUTF("登录成功,欢迎回来");
}else{
dos.writeUTF("用户名或密码错误");
}
dis.close();
dos.flush();
client.close();
}
}