为了完成 客户端通过键盘录入用户名服务器端对这个用户名进行校验,如果用户存在,在服务器端显示xxx已经登录;如果用户不存在,在服务器端显示xxx尝试登录,并在客户端显示用户名不存在,最多登录三次
服务器端
package fourth;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class LoginServer {
public static void main(String[] args) {
try {
ServerSocket ss=new ServerSocket(10010);
while(true){
Socket s=ss.accept();
new Thread(new UserThread(s)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class UserThread implements Runnable{
Socket s;
public UserThread(Socket s) {
this.s=s;
}
@Override
public void run() {
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"...connecting...");
try {
for(int i=0 ;i<3;i++){
BufferedReader brIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
String name=brIn.readLine();
BufferedReader br=new BufferedReader(new FileReader("E:\\user.txt"));
PrintWriter out=new PrintWriter(s.getOutputStream());
String line=null;
boolean flag=false;
while (null!=(line=br.readLine())) {
if (line.equals(name)) {
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) {
e.printStackTrace();
}
}
}
客户端
package fourth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class LoginClient {
public static void main(String[] args) {
try {
Socket s=new Socket(InetAddress.getLocalHost(), 10012);
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
BufferedReader brIn =new BufferedReader(
new InputStreamReader(s.getInputStream()));
for(int i=0; i<3;i++){
String line=br.readLine();
if(line==null)
break;
out.write(line);
String info=brIn.readLine();
System.out.println("info"+info);
if (info.contains("欢迎"))
break;
}
br.close();
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
|