问题描述
sendFXML(asByteArray(getrequiredScene(fetchSceneRequest())));
private void sendFXML(byte[] requiredFXML) throws IOException,TransformerException {
dataOutputStream.write(requiredFXML);
dataOutputStream.flush();
}
private Document getrequiredScene(String requiredFile) throws IOException,ParserConfigurationException,SAXException,TransformerException {
return new XMLLocator().getDocumentOrReturnNull(requiredFile);
}
private String fetchSceneRequest() throws IOException,ClassNotFoundException {
return dataInputStream.readUTF();
}
在 XMLLocator 一侧,它找到正确的文档并正确解析它。我通过在控制台中打印整个文档来查看它。 但我无法在客户端通过以下方式处理它:
public static void receivePage() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] data = new byte[989898];
int bytesRead = -1;
while((bytesRead = dataInputStream.read(data)) != -1 ) { //stops here
baos.write(data,bytesRead );
}
Files.write(Paths.get(FILE_TO_RECEIVED),data);
}
在 while() 循环中的第一次迭代后,它只是停在评论的地方。 我不知道服务器端是否有错误,我以不正确的格式将其发送到文档中,或者我错误地读取了发送的字节数组。问题出在哪里?
编辑: 出于调试目的,在 receivePage() 方法中,我选择了一种从服务器读取字节数组的不同方式,如下所示:
int count = inputStream.available();
byte[] b = new byte[count];
int bytes = dataInputStream.read(b);
System.out.println(bytes);
for (byte by : b) {
System.out.print((char)by);
}
现在我可以在控制台中打印获取的 FXLM,但出现了一个新问题。 在调试时,它通常从服务器接收字节 [],为 count 写入 2024 并显示文件的内容,但如果我通过 Shift 正常运行应用程序+ f10 它什么也不获取,只在控制台中写入 0
编辑 2: 出于某种原因,再一次,在调试时,它甚至可以写入文件
for (byte by : b) {
Files.write(Paths.get(FILE_TO_RECEIVED),b);
System.out.print((char)by);
}
但是当我尝试在调试时返回这个 fxml 然后显示如下:
Parent fxmlToShow = FXMLLoader.load(getClass().getResource("/network/gui.fxml"));
Scene childScene = new Scene(fxmlToShow);
Stage window = (Stage)((Node)ae.getSource()).getScene().getwindow();
window.setScene(childScene);
return window;
它只显示以前的文件。就像第一次调试时一样,当我从服务器请求第一个时,它显示一个空白页面。在第二次尝试调试时,当我从服务器请求第 3 页时,它向我显示了之前询问的页面,依此类推。 对我来说,这似乎绝对是疯了,因为 fxml rile 实际上在行之前刷新
Parent fxmlToShow = FXMLLoader.load(getClass().getResource("/network/gui.fxml"));
被调用。
解决方法
好的,感谢大家的参与。
因此,如果 FXML 文件是由错误的 FILE_TO_RECEIVED 路径引起的,则显示不正确的问题。
当 FXMLLoader.load(getClass().getResource("/network/gui.fxml"));
加载 gui.fxml
时,它不是从 D:\\JetBrains\\IdeaProjects\\Client\\src\\network\\gui.fxml
,我的情况,而是从 D:\\JetBrains\\IdeaProjects\\Client\\OUT\\PRODUCTION\\Client\\network\\gui.fxml
。
对我来说,这似乎并不明显。
调试和运行时的不同行为呢?在方法 receivePage() 中,它需要等到连接可用。
int count = inputStream.available();
如果您阅读有关此方法的文档,您会看到
返回可以从此输入流读取(或跳过)的字节数的估计值... InputStream 类的可用方法总是返回 0...
因此,您需要等待连接可用
while(inputStream.available()==0){
Thread.sleep(100);
}
否则它只会为 0 个字节准备 byte[] b = new byte[count];
而你什么也不能写。