我正在学习 Java 套接字编程,并决定做一个简单的登录/注册应用程序,并将用户数据保存到文件中。连接客户端 - 服务器工作正常,直到我尝试注册新用户。输入用户数据后,程序将其保存到文件中,然后连接以某种方式停止工作。我仍然可以在控制台上写东西,但它无处可去。告诉我我做错了什么。
PS:我对 Java 也有点陌生。
我的客户沟通
public void clientCommunication() throws IOException {
String line;
String response;
Scanner scanner = new Scanner(System.in);
do{
line = scanner.nextLine();
out.println(line);
response = in.readLine();
System.out.println(response);
}while(!line.equals("quit"));
}
我的服务器通信
public void serverCommunication() throws IOException{
String line = in.readLine();
while (line != null) {
switch (line) {
case "login" -> loginUser();
case "register" -> registerUser();
case "quit" -> out.println("Closing connection");
default -> out.println("Unknown command");
}
line = in.readLine();
}
}
用户注册方法
private void registerUser() throws IOException {
File data = new File("data.txt");
if(!data.exists()){
data.createNewFile();
}
BufferedWriter fileOut = new BufferedWriter(new FileWriter(data,true));
String name;
String login;
String password;
out.println("Enter your full name:");
name = in.readLine();
out.println("Enter login:");
login = in.readLine();
out.println("Enter password:");
password = in.readLine();
fileOut.write(login + " " + password + " " + name + "\n");
System.out.println("New user created.");
fileOut.close();
}