java客戶端登陸服務器用戶名驗證
更新時間:2016年05月20日 16:09:45 作者:chaoyu168
這篇文章主要為大家詳細介紹了java客戶端登陸服務器用戶名驗證的相關資料,需要的朋友可以參考下
本文實例為大家分享了java客戶端登陸服務器用戶名驗證的具體實現(xiàn)代碼,供大家參考,具體內容如下
客戶端通過鍵盤錄入用戶名,服務端對用戶名進行驗證。
如果用戶名存在,服務端顯示xxx已登錄,客戶端顯示xxx,歡迎登陸。
如果用戶名不存在,服務端顯示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);//建立服務 BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//讀取鍵盤輸入用戶名 PrintWriter pw = new PrintWriter(s.getOutputStream(),true);//讀到數(shù)據(jù)往服務端寫 BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));//將客戶端返回的數(shù)據(jù)讀入 for(int x = 0;x < 3; x ++)//只登陸3次設定 { String line = bufr.readLine();//讀取用戶名 pw.println(line); if(line == null)//為空用戶名終止 break; pw.println(line); String info = bufin.readLine();//讀取服務端返回的數(shù)據(jù) System.out.println("Server info:"+info); if(info.contains("歡迎登陸"))//用戶登錄終止 break; } bufr.close(); s.close(); } } /* *服務端 */ 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);//寫入流,服務端寫出 String line = null; boolean flag = false;//判斷標記 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);//建立服務 while (true) { Socket s = ss.accept();//接收客戶端傳來數(shù)據(jù) new Thread(new ServerThread(s)).start();//開啟線程 } } }
打印結果:
user.txt
以上就是本文的全部內容,希望對大家的學習有所幫助。
相關文章
springMVC的RequestMapping請求不到路徑的解決
這篇文章主要介紹了springMVC的RequestMapping請求不到路徑的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Java連接并操作Sedna XML數(shù)據(jù)庫的方法
這篇文章主要介紹了Java連接并操作Sedna XML數(shù)據(jù)庫的方法,較為詳細的說明了Sedna XML數(shù)據(jù)庫的原理與功能,并給出了基于java操作Sedna XML數(shù)據(jù)庫的方法,需要的朋友可以參考下2015-06-06