所以我只是重新编写这段代码:
public static void main (String[] args) throws IOException{
DatagramSocket serverSocket = new DatagramSocket(1500);
while(true){
byte[] recieveData = null; //<---look at this #############!!!
DatagramPaket recievePaket = new DatagramPacket (recieveData, recieveData.length);
serverSocket.receive(recievePaket);
String text = recieveData.toString();
if (text.equals("exit")){
serverSocket.close();
System.exit(42);
}else if (text.equals("scan")){
scan();
}
}
}
现在我知道DatagramPacket需要一个缓冲区但是如何通过“null”初始化呢?如果一个人不想存储收到的数据但是如何看到“退出”或“扫描”是否被发送,那对我来说是有意义的吗? 最重要的是,在没有收到数据包之前,如何知道缓冲区需要的大小?
答案 0 :(得分:1)
以下作品:
public static void main (String[] args) throws IOException {
try (DatagramSocket socket = new DatagramSocket(PORT_NUMBER)) {
boolean loop = true;
final byte[] buffer = new byte[BUFFER_SIZE];
final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (loop) {
socket.receive(packet);
final String text = new String(packet.getData()).trim();
switch (text) {
case "exit":
loop = false;
break;
case "scan":
scan();
break;
default:
System.err.printf("Received unknown command `%s`%n", text);
}
}
}
}
不幸的是你必须设置缓冲区大小。
我所做的更改包括:
exit\n
不等于exit