java客戶端登陸服務(wù)器用戶名驗證
本文實例為大家分享了java客戶端登陸服務(wù)器用戶名驗證的具體實現(xiàn)代碼,供大家參考,具體內(nèi)容如下
客戶端通過鍵盤錄入用戶名,服務(wù)端對用戶名進(jìn)行驗證。
如果用戶名存在,服務(wù)端顯示xxx已登錄,客戶端顯示xxx,歡迎登陸。
如果用戶名不存在,服務(wù)端顯示xxx嘗試登陸,客戶端顯示xxx,用戶名不存在。
最多登陸三次,防止暴力登陸。
import java.io.*;
import java.net.*;
/*
*客戶端
*/
class client
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.33.1",10008);//建立服務(wù)
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//讀取鍵盤輸入用戶名
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);//讀到數(shù)據(jù)往服務(wù)端寫
BufferedReader bufin =
new BufferedReader(new InputStreamReader(s.getInputStream()));//將客戶端返回的數(shù)據(jù)讀入
for(int x = 0;x < 3; x ++)//只登陸3次設(shè)定
{
String line = bufr.readLine();//讀取用戶名
pw.println(line);
if(line == null)//為空用戶名終止
break;
pw.println(line);
String info = bufin.readLine();//讀取服務(wù)端返回的數(shù)據(jù)
System.out.println("Server info:"+info);
if(info.contains("歡迎登陸"))//用戶登錄終止
break;
}
bufr.close();
s.close();
}
}
/*
*服務(wù)端
*/
class ServerThread implements Runnable
{
private Socket s;
ServerThread(Socket s)
{
this.s = s;
}
public void run()
{
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"...........connect");
try
{
for(int x = 0;x < 3;x ++)
{
BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));//讀取客戶端發(fā)送的數(shù)據(jù)
String name = bufin.readLine();
if(name == null)
break;
BufferedReader bufr = new BufferedReader(new FileReader("user.txt"));//讀取已存入用戶賬戶,本來是讀取數(shù)據(jù)庫,這里方便就寫了一個文本
PrintWriter out = new PrintWriter(s.getOutputStream(),true);//寫入流,服務(wù)端寫出
String line = null;
boolean flag = false;//判斷標(biāo)記
while((line = bufr.readLine())!= null)//讀取數(shù)據(jù)庫(Use.txt)中數(shù)據(jù)
{
if(line.equals(name))//如果數(shù)據(jù)庫和讀取用戶名相同,則終止
{
flag = true;
break;
}
}
if(flag)
{
System.out.println(name+":已登錄");
out.println(name+":歡迎登陸");
break;
}
else
{
System.out.println(name+":嘗試登陸");
out.println(name+":用戶名不存在");
}
}
s.close();
}
catch (Exception e)
{
throw new RuntimeException("驗證失敗");
}
}
}
class server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10008);//建立服務(wù)
while (true)
{
Socket s = ss.accept();//接收客戶端傳來數(shù)據(jù)
new Thread(new ServerThread(s)).start();//開啟線程
}
}
}
打印結(jié)果:

user.txt

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
java foreach循環(huán)為什么不能賦值的講解
這篇文章主要介紹了java foreach循環(huán)為什么不能賦值的講解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
SpringBoot啟動時自動執(zhí)行指定方法的幾種實現(xiàn)方式
在Spring Boot應(yīng)用程序中,要實現(xiàn)在應(yīng)用啟動時自動執(zhí)行某些代碼,本文主要介紹了SpringBoot啟動時自動執(zhí)行指定方法的幾種方式,文中有相關(guān)的代碼示例供大家參考,需要的朋友可以參考下2024-03-03
Springboot?jpa使用sum()函數(shù)返回結(jié)果如何被接收
這篇文章主要介紹了Springboot?jpa使用sum()函數(shù)返回結(jié)果如何接收,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
細(xì)數(shù)java for循環(huán)中的那些坑
這篇文章主要介紹了Java for循環(huán)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07

