1. 程式人生 > >多client並發登錄

多client並發登錄

public -m user info sta thread lin implement ont

//LoginClient.java

package mySocket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


/**
 *client通過鍵盤錄入username
 *服務端對這個username進行校驗。
 *
 *假設該用戶存在,在服務端顯示xxx,已登錄。
 *並在client顯示xxx,歡迎光臨。

* *假設該用戶存在,在服務端顯示xxx。嘗試登陸。 *並在client顯示xxx,該用戶不存在。 * *最多登陸3次。 */ public class LoginClient { public static void main(String[] args) throws Exception { Socket s = new Socket("192.168.1.103",10008); BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(s.getOutputStream(),true); BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); for(int x=0;x<3;x++) { //讀鍵盤 String line = bufr.readLine(); if(line==null) break; //發出去 out.println(line); //讀取服務端反饋 String info = bufIn.readLine(); System.out.println(info); if(info.contains("歡迎")) break; } bufr.close(); s.close(); } }


//LoginServer.java


package mySocket;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;


class LoginThread implements Runnable	{
		private Socket s; 
		public LoginThread(Socket s) {
			this.s = s;
		}
		public void run() {
			//獲取連接的ip
			String ip = s.getInetAddress().getHostAddress();
			System.out.println(ip+"已被連接");
			
			try {
					for(int x=0;x<3;x++)	{
							BufferedReader bufIn =
									new BufferedReader(new InputStreamReader(s.getInputStream()));
							//讀取client發來的數據
							String name = bufIn.readLine();
							if(name==null)
								break;
							//讀取user.txt裏的數據
							BufferedReader bufr = 
									new BufferedReader(new FileReader("user.txt"));
							
							String line = null;
							boolean flag = false;
							
							while((line=bufr.readLine())!=null)	{
									if(line.equals(name))	{
										flag = true;
										break;
									}
							}
							
							PrintStream out = new PrintStream(s.getOutputStream(),true);
							if(flag)	{
								System.out.println(name+"已登錄");
								 out.println(name+"歡迎光臨");
								 break;
							}
							else{
								System.out.println(name+"嘗試登陸");
								out.println(name+"username不存在");
							}
							
							s.close();
					}
			} catch (Exception e) {
						throw new RuntimeException(ip+"校驗失敗");
			}
		}
}

public class LoginServer {

	public static void main(String[] args) throws Exception {
			ServerSocket ss = new ServerSocket(10008);
			
			while(true)	{
				Socket s = ss.accept();
				new Thread(new LoginThread(s)).start();
			}
	}

}

//學習自畢向東老師培訓視頻


多client並發登錄