Tcp实现双向登录
public class DemoTwoClient {
public static void main(String[] args) throws IOException {
System.out.println("========定义客户端=========");
Socket client = new Socket("localhost",9898);
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入用户名:");
String username = rd.readLine();
System.out.println("请输入密码:");
String password = rd.readLine();
DataOutputStream os = new DataOutputStream(client.getOutputStream());
os.writeUTF("username="+username+"&password="+password);
DataInputStream is = new DataInputStream(client.getInputStream());
System.out.println(is.readUTF());
if (is!=null){
is.close();
}
if (os!=null){
os.close();
}
rd.close();
client.close();
}
}
public class DemoTwoClient02 {
static int i = 1;
public static void main(String[] args) throws IOException {
System.out.println("=========定义服务器端===============");
ServerSocket serverSocket = new ServerSocket(9898);
Socket client = serverSocket.accept();
System.out.println("第"+(i++)+"个客户端正在连接");
String username = "";
String password = "";
DataInputStream is = new DataInputStream(client.getInputStream());
String str = is.readUTF();
String [] strings = str.split("&");
for (String string : strings) {
String[] arr = string.split("=");
if ("username".equals(arr[0]))
username = arr[1];
else if ("password".equals(arr[0]))
password = arr[1];
}
DataOutputStream os = new DataOutputStream(client.getOutputStream());
if ("zhangsan".equals(username)&&"123".equals(password)){
os.writeUTF("登录成功");
}
else
os.writeUTF("登录失败");
if (os!=null){
os.close();
}
if (is!=null){
is.close();
}
client.close();
serverSocket.close();
}
}