I made a basic server using sockets and wanted to add a simple GUI to turn it on and off. To make the GUI still work while the server is running a while-loop, i created a thread for the sockets. Now what i was thinking of was adding a boolean to that while-loop which exits said loop and causes the server to stop when pressing a button in the GUI.
Now the problem is that the boolean is set in the GUI thread and needs to be called in the server thread. I read about setting the boolean to volatile or using an AtomicBoolean but neither of them seemed to work. Is there maybe something special i need to look for when calling the boolean from the server thread?
This is the (simplified) code i wrote so far:
public class GUI {
private static int port = 12345;
private static volatile boolean online = false;
public static void main(String[] args) {
//GUI works so i left the code out
//Basically generates a button giving it the actionlistener below
}
private static ActionListener getActionListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!online) {
online = true;
Thread serverThread = new Thread(new ServerThread());
serverThread.start();
} else {
online = false;
}
}
};
}
public static boolean getOnlineState() {
return online;
}
public static int getPort() {
return port;
}
}
and the class containing the server thread:
public class ServerThread implements Runnable {
@Override
public void run() {
try {
ServerSocket serSoc = new ServerSocket(GUI.getPort());
Socket cliSoc = serSoc.accept();
PrintWriter out = new PrintWriter(cliSoc.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cliSoc.getInputStream()));
String input;
while(GUI.getOnlineState()) {
while((input = in.readLine()) != null) {
out.println(input);
}
}
out.println("Stopping");
cliSoc.shutdownInput();
cliSoc.shutdownOutput();
cliSoc.close();
serSoc.close();
out.close();
in.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Since i'm new to all this multithreading stuff, there might be some other mistakes which i'd be glad if you would tell me about.
readline()also needs to be interrupted. See answers to stackoverflow.com/questions/3595926/…