To try to illustrate the situation:
I created the SocketManager class. This extends the JavaFX service and is designed to create new threads (the JavaFX task that I expanded and called SocketListener), which handles specific socket connections.
Inside SocketListener, I have a loop that listens for input through a socket (and returns a response to the client).
Problem : The loop inside the SocketListener is blocked (obviously). This means that I never achieve a “return” inside the Socket Listener invocation method (which extends the JavaFX Task). I am curious about which template to implement so that I can return a value from SocketListener without breaking my loop, which maintains a client connection. One of the ideas that came to mind was to create a special event to trigger when each message got through the socket, but I want to make sure that everything that I implement is not just “working”, but also optimal.
Here is the code for the two classes I am referring to:
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketManager extends Service<SocketMessage> {
int listenPort;
ServerSocket server;
public SocketManager(int listenPort){
this.listenPort = listenPort;
try {
this.server = new ServerSocket(listenPort);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public int getListenPort() {
return listenPort;
}
public void setListenPort(int listenPort) {
this.listenPort = listenPort;
}
@Override
protected Task createTask() {
String returnedMessage;
Socket client;
SocketListener messenger;
while(true){
try {
client = null;
client = server.accept();
messenger = new SocketListener(client);
new Thread(messenger).start();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
And another
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketListener extends javafx.concurrent.Task<String> {
private final Socket client;
private PrintWriter clientOut;
private int messageCount = 0;
public SocketListener(Socket client){
this.client = client;
try {
this.clientOut = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected String call() throws Exception {
String nextLine = null;
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
clientOut.println("Just saying hi.");
while ((nextLine = in.readLine()) != null) {
this.messageCount++;
clientOut.println("You've messaged me " + this.messageCount + " times.");
}
return "Socket closed.";
}
}
source
share