在Java的客户机-服务器体系结构中,在何处放置循环以获得更好的结果?
我有一个Java的客户机-服务器体系结构,我需要在其中放置一个循环。 我花了一些时间考虑把这个循环放在哪里,但无论我在哪里尝试都没有得到预期的结果 这是我的client.java:在Java的客户机-服务器体系结构中,在何处放置循环以获得更好的结果?,java,sockets,client-server,Java,Sockets,Client Server,我有一个Java的客户机-服务器体系结构,我需要在其中放置一个循环。 我花了一些时间考虑把这个循环放在哪里,但无论我在哪里尝试都没有得到预期的结果 这是我的client.java: public class Client { private static Scanner scanner; public static void main(String[] args) throws IOException { scanner = new Scanner(Syste
public class Client {
private static Scanner scanner;
public static void main(String[] args) throws IOException {
scanner = new Scanner(System.in);
// set up server communication
Socket clientSocket = new Socket(InetAddress.getLocalHost(), 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
System.out.println("Enter pin : ");
String password = scanner.next();
// send PIN to server
out.println(password);
out.flush();
// get response from server
String response = in.readLine();
System.out.println(response);
scanner.close();
in.close();
out.close();
clientSocket.close();
}
}
这是我的server.java:
public class Server {
private static ServerSocket server;
public static void main(String[] args) throws Exception {
server = new ServerSocket(1234);
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
// Listen for client requests:
String request = in.readLine();
while (request != null) {
// check PIN, send result
boolean pinCorrect = checkPin(request);
out.println(pinCorrect ? ":)" : ":(");
out.flush();
}
out.close();
in.close();
socket.close();
}
}
如果用户没有准确输入4位数字,我需要重复这个过程,因此我一直在考虑一个do{}while(pinSize!=4)
循环
但是当我把它放在服务器上时,我总是有错误的输出“:)”或“:”(
而不是“Pin必须是4位”
,然后我尝试输入客户端部分,但这一次我总是有可能只输入一个Pin,所以循环没有那么有效
实际上,这是一些我将放入循环中的代码:
if (pinSize != 4) {
System.out.println("Pin must be 4 digits");
} else {
System.out.println("Checking...");
}
有什么想法吗?谢谢。将签入客户端代码。有关更多信息,请阅读内联注释
- 首先使用
代替nextLine()
一次读取一整行next()
- 密码的验证检查及其长度检查
...
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
System.out.println("Enter pin : ");
String password = null;
// 4 digits pattern
Pattern p = Pattern.compile("\\d{4}");
while (true) {
password = scanner.nextLine();
int pinSize = password.length();
if (pinSize == 4) {
Matcher m = p.matcher(password);
if (m.find()) {
System.out.println("Checking " + password);
break;
} else {
System.out.println("Pin must be 4 digits");
}
} else {
System.out.println("Pin must be 4 digits");
}
}
// send PIN to server
out.println(password);
...
您在服务器中的何处放置
循环
?如果您没有为每个请求打开新连接,则必须添加一些学习方法,以了解新字符是前一个PIN的一部分或是新PIN的开始。当您说重复该过程时,您的意思是让服务器再次侦听下一个输入吗?如果是,则在每个新连接上在上,生成一个新线程来处理该连接,这样您的服务器就可以回去监听更多内容了?如果您不在代码中的任何地方打印它,您如何获得输出“Pin必须是4位”
?@SJuan76我将它放在while(request!=null)
循环之前,然后立即结束它。所有关闭();
不在我的循环中。是否正确?在扫描仪输入中添加一个条件,如果用户未输入4位数字,请不要将其发送到服务器?