我编写了一小段概念验证代码,应该执行以下操作:
按下按钮 1 打开到服务器的套接字并传递身份验证详细信息并收集服务器响应以供显示。 (这100%有效,身份验证成功。)
按下按钮 2 应该发送请求服务器状态的命令,这是不起作用的部分。我可以从服务器返回的唯一响应是“等待身份验证”,尽管我通过按按钮 1 成功做到了这一点。
看起来,在按下初始按钮 1 后,套接字正在关闭,因此忽略按钮 2 代码,而是再次等待身份验证。
问题:如何使用按钮 1 打开套接字,然后使用按钮 2 在服务器上触发其他命令。
我已经尝试过s.setKeepAlive(true);
和s.setSoTimeout(60000);
并且还将套接字方法放入线程中,但没有什么乐趣。
My Controller.java(观察按钮 1 和 2 的按下情况)
public class Controller {
@FXML public Button auth;
@FXML public Button status;
public void balls(ActionEvent event) throws IOException{
(new Thread(new helloRunnable())).start();
}
public void balls2(javafx.event.ActionEvent event)throws IOException {
sample.Main.status();
}
}//end class
我的helloRunnable.Java(完美运行)
public class helloRunnable implements Runnable {
public void run() {
try {
Socket s = new Socket("192.168.16.230", 63333);
s.setKeepAlive(true);
s.setSoTimeout(60000);
PrintStream p = new PrintStream(s.getOutputStream(), true);
BufferedReader bufRd = new BufferedReader(new InputStreamReader(s.getInputStream()));
p.println("{\"method\":\"authentication\",\"server_password\":\"g4t3w4y1\"}");
String response = bufRd.readLine();
System.out.println(response);
p.println("");
response = bufRd.readLine();
System.out.println(response);
} //end try block
catch (IOException e) {
System.err.println(e.getMessage());
} //end catch
}//end runnable
}//end class
My Main.Java(正在等待再次验证,因为它出现套接字重置/关闭)
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Button Test");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void status() throws IOException{
Socket s = new Socket("192.168.16.230", 63333);
PrintWriter p = new PrintWriter(s.getOutputStream(), true);
BufferedReader bufRd = new BufferedReader(new InputStreamReader(s.getInputStream()));
p.println("");
p.println("{ \"method\":\"get_server_status\" }");
String response = bufRd.readLine();
//Object obj = JSONValue.parse(response);
//JSONObject jsonObject = (JSONObject) obj;
//String reply = (String) jsonObject.get("reply");
//System.out.println("Reply: " + reply + "\n");
System.out.println(response);
}
}//end main class
我已经尝试了在这里和其他地方找到的各种修复,但似乎无法修复它。请指出我正确的方向。令人沮丧的是,基于 CLi 的版本范围更大,但运行得很好。我进行了身份验证,并且套接字保持打开状态。我可以整天在服务器上发出不同的命令。
无论如何,提前感谢您提供的任何帮助。
最佳答案
当然,它会再次要求身份验证,因为您在每次运行时都会创建一个新套接字 相反,您想创建套接字一次(或至少在一定时间内)并在每次运行时重复使用它......所以......您需要存储套接字/并配置它
关于java - 套接字似乎在按下按钮之间关闭,如何保持它打开? JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48545768/