I have a simple JavaFX app when I start the app it extablishes a connection with a server via Socket and listen for data from this server continously. Now I have a created a Button that should send dat to server.
This is how I did it
Controller:
@FXML
private Button update;
public void askOnline() throws UnknownHostException, IOException{
Socket socket = new Socket("127.0.0.1", 7000);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("AreYouOnline");
dos.flush();
socket.close();
}
Main:
@Override
public void start(Stage primaryStage) throws IOException {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Thypheon Application");
initRootLayout();
controller2 = initDesign();
addBot();
con = new Connection(controller2);
Thread t = new Thread(con);
t.start();
}
Thread:
public class Connection implements Runnable {
String result;
Controller controller;
Socket socket;
DataOutputStream dos;
public Connection(Controller controller) {
this.controller = controller;
}
@Override
public void run() {
try {
socket = new Socket("127.0.0.1", 7000);
System.out.println("Connessooo");
DataInputStream dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
SeiOnline so = new SeiOnline(dos);
Thread t = new Thread(so);
t.start();
while(true){
result = dis.readUTF();
System.out.println(result);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
In this way I create a new Socket connection between Client and Server just to send data. But my question is this: Is possible to retrieve the already existing Socket connection (running in the thread) and use it in order to send data to server, instead of create a new Socket Connection?