多client并发登录
//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(); } } }
//学习自毕向东老师培训视频