写了一下客户端登陆的程序,麻烦给看一下哪里出的问题
客户端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class LoginClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 8000);
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 : " + info);
//info是服务器端发过来的信息,为什么是null呢
if(info.contains("欢迎"))
//在这一句报出 空指针异常
break;
}
bufr.close();
s.close();
}
}
服务器端
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;
class UserThread implements Runnable {
private Socket s;
public UserThread(Socket s) {
this.s = s;
}
public void run() {
String ip = s.getInetAddress().getHostAddress();
System.out.println("------ " + ip + " connected -------");
try {
for(int i=0; i<3; i++) {
BufferedReader bufIn =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String name = bufIn.readLine();
BufferedReader bufr = new BufferedReader(new FileReader("user.txt"));
PrintWriter out = new PrintWriter(s.getOutputStream());
boolean flag =false;
String line = null;
while((line = bufr.readLine()) != null) {
if(line.equals(name)) {
flag = true;
break;
}
}
if(flag) {//如果flag为true
System.out.println(name + ", 已登录");
out.print(name + ", 欢迎光临");
break;
} else {
System.out.println(name + ", 尝试登录");
out.println(name + ", 用户名不存在");
}
}
s.close();
} catch (Exception e) {
throw new RuntimeException(ip + "校验失败");
}
}
}
public class LoginServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8000);
while(true) {
Socket s = ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
user.txt的内容
diyige
dierge
disange
|