为什么扫描仪在Java中不能正常工作?
因此,我正在用java编写一个客户机-服务器程序,重点是更改服务器上的数据。以下是客户端的代码:为什么扫描仪在Java中不能正常工作?,java,Java,因此,我正在用java编写一个客户机-服务器程序,重点是更改服务器上的数据。以下是客户端的代码: package com.company; import java.io.IOException; import java.net.*; import java.util.Scanner; public class Client { public static void main(String[] args){ try { DatagramSocke
package com.company;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args){
try {
DatagramSocket socket=new DatagramSocket(4001);
while(true){
Scanner jin=new Scanner(System.in);
String text=jin.nextLine();
byte[] word=new byte[256];
int command=Integer.parseInt(text);
word=text.getBytes();
DatagramPacket packet=new DatagramPacket(word, word.length, InetAddress.getByName("localhost"), 4000);
socket.send(packet);
if (command==0){
word=new byte[256];
packet=new DatagramPacket(word, word.length);
socket.receive(packet);
word=packet.getData();
System.out.println(new String(word));
}
else if (command==1){
word=new byte[256];
packet=new DatagramPacket(word, word.length);
socket.receive(packet);
System.out.println(new String(word));
int broj=jin.nextInt();
word=Integer.toString(broj).getBytes();
packet=new DatagramPacket(word, word.length, InetAddress.getByName("localhost"), 4000);
socket.send(packet);
word=new byte[256];
packet=new DatagramPacket(word, word.length);
socket.receive(packet);
System.out.println(new String(word));
new ClientHandler(socket).start();
}
else if(command==2){
word=new byte[256];
packet=new DatagramPacket(word, word.length);
socket.receive(packet);
System.out.println(new String(word));
jin=new Scanner(System.in);
int broj=Integer.parseInt(jin.next());
System.out.println("Test");
byte[] word1=Integer.toString(broj).getBytes();
System.out.println(new String(word1));
packet=new DatagramPacket(word1, word1.length, InetAddress.getByName("localhost"), 4000);
socket.send(packet);
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
问题在于if语句,其中:
else if (command==2)
在我输入一个有效的数字后,程序不会前进。经过一些调试,我发现问题出在扫描仪或:
int broj=Integer.parseInt(jin.next());
扫描仪没有注册输入值,也没有打印“测试”,程序被卡住。有人知道解决办法吗
nextLine
和任何其他下一个方法混合使用。要么只使用nextLine,要么永远不要使用nextLine。如果要获取“下一个字符串,直到换行符”(与“下一个字符串直到空格,这是next()
通常所做的),请设置分隔符:scanner。使用分隔符(“\r?\n”)
在创建扫描仪后立即表示next()
现在将获取整行注意:您通常会看到关于在非下一次通话后插入额外
nextLine
的建议。这是一个非常普遍但很糟糕的建议。改为修复分隔符,如上所述。可能相关(现在无法验证):不要在系统中创建多个扫描仪对象。移动扫描仪jin=新扫描仪(System.in)
在try
语句之前排队,然后删除jin=新扫描仪(System.in)在else if(command==2){
块中的code>行。然后按照@Pshemo提供的链接中的建议操作。您的代码对我有效。我认为问题在于客户端一直在等待响应socket.receive(packet)
,这将阻止线程,直到它得到响应。考虑将其移动到另一个线程,或者确保应用程序得到响应,我使用Netcat使用以下cmdnc-u localhost 4001模拟客户端。