聊天室實現-客戶端實現
阿新 • • 發佈:2019-01-19
cli write username flag equal else ace 釋放 clinet
public class ClientSide { //服務端IP private String serverIP; //端口號 private int port; public ClientSide(String serverIP,int port){ this.serverIP=serverIP; this.port=port; } public void initClient(){ try{ //創建socket,連接服務端 Socket client=new Socket(serverIP,port); //新建讀取信息緩存區 BufferedReader bufferedReader=null; //新建寫入字符流 PrintWriter printWriter=null; //控制臺輸入 Scanner scanner = new Scanner(System.in); //獲得輸入流,將數據載入緩存區 bufferedReader=new BufferedReader(new InputStreamReader(client.getInputStream())); //輸出流,true為開啟自動釋放flush printWriter=new PrintWriter(client.getOutputStream(),true); //接收歡迎詞 System.out.println(readMessage(bufferedReader)); String flag=""; while (!flag.equals(Config.LoginSuccessCode)){ //接收‘輸入用戶名‘ System.out.println(readMessage(bufferedReader)); //控制臺輸入 String username = scanner.nextLine(); sentMessage(printWriter,username); //接收‘輸入密碼‘ System.out.println(readMessage(bufferedReader)); //控制臺輸入 String psw = scanner.nextLine(); sentMessage(printWriter,psw); //得到登錄結果 flag=readMessage(bufferedReader); if(Config.LoginErrCode.equals(flag)){ System.out.println("---用戶名密碼不匹配,請重新登錄!---"); } } System.out.println("---歡迎使用聊天室,祝你聊天愉快---"); //登錄成功,開始聊天 if(flag.equals(Config.LoginSuccessCode)){ //讀取信息線程 new ReadClientThread(client.getInputStream()).start(); //輸入信息線程 new SentClientThread(printWriter).start(); }else{ System.out.println("登錄異常!"); } }catch (Exception e){ System.out.println("發生異常,請聯系管理員!"); } } /** * 讀取信息 * @param bufferedReader */ public String readMessage(BufferedReader bufferedReader) { String clinetMessage=null; try { clinetMessage= bufferedReader.readLine(); // System.out.println("服務端:"+clinetMessage); }catch (Exception e){ System.out.println("發生異常,請聯系管理員!"); //e.printStackTrace(); } return clinetMessage; } /** * 發送信息 * @param printWriter * @param message */ public void sentMessage(PrintWriter printWriter,String message){ printWriter.println(message); printWriter.flush(); } public static void main(String[] args){ ClientSide clientSide=new ClientSide("127.0.0.1",5000); clientSide.initClient(); } }
參考鏈接:https://blog.csdn.net/BlueSky_USC/article/details/54414860
聊天室實現-客戶端實現